android文件上传示例分享(android图片上传)

主要思路是调用系统文件管理器或者其他媒体采集资源来获取要上传的文件,然后将文件的上传进度实时展示到进度条中。

主Activity

复制代码 代码如下:
package com.guotop.elearn.activity.app.yunpan.activity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Audio.Media;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;

import com.guotop.base.activity.BaseActivity;
import com.guotop.base.util.MyFile;
import com.guotop.elearn.activity.R;
import com.guotop.elearn.activity.app.yunpan.item.YunPanUploadFileItem;

/**
 *
 *
 * @author: 李杨
 * @time: 2014-4-15下午4:29:35
 */
public class YunPanUploadFileActivity extends BaseActivity implements OnClickListener{

String userId, parentId;
    private final static int FILECHOOSER_RESULTCODE = 0;
//    private String openFileType="";
    private String mVideoFilePath,mPhotoFilePath,mVoiceFilePath;
    private Button chooseBtn,uploadBtn;
    private LinearLayout conterLayout;
    private String actionURL;

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState, this);
        setTitle("云盘上传文件");
        setContentView(R.layout.activity_yunpan_uploadfile);

userId = getIntent().getStringExtra("userId");
        parentId = getIntent().getStringExtra("parentId");
        actionURL = getIntent().getStringExtra("actionURL");

chooseBtn = (Button)findViewById(R.id.chooseBtn);
        uploadBtn = (Button)findViewById(R.id.uploadBtn);
        conterLayout = (LinearLayout)findViewById(R.id.conterLayout);

chooseBtn.setOnClickListener(this);
        uploadBtn.setOnClickListener(this);

}

@Override
    public void onClick(View v) {
        if(v.getId()==R.id.chooseBtn){
//            //选择文件       
            startActivityForResult(createDefaultOpenableIntent(), YunPanUploadFileActivity.FILECHOOSER_RESULTCODE);

//            Intent intent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
//            startActivityForResult(intent, YunPanUploadFileActivity.FILECHOOSER_RESULTCODE);

//              Intent intent = new Intent(Media.RECORD_SOUND_ACTION);
//            ((Activity) context).startActivityForResult(intent, YunPanUploadFileActivity.FILECHOOSER_RESULTCODE);
        }else if(v.getId()==R.id.uploadBtn){
            //上传文件

}
    }

/**
     * 创建上传文件
     */
    public void createUploadFileItem(String filePath){
//        View view = LayoutInflater.from(context).inflate(R.layout.activity_yunpan_uploadfile_item, null);

new YunPanUploadFileItem(context, conterLayout, filePath,actionURL);

}

@Override
    public void onConfigurationChanged(Configuration newConfig) {
        // TODO Auto-generated method stub
        super.onConfigurationChanged(newConfig);
    }

/**选择文件*/
    private Intent createDefaultOpenableIntent() {
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.putExtra(Intent.EXTRA_TITLE, "选择文件");
        i.setType("*/*");

Intent chooser = createChooserIntent(createCameraIntent(), createCamcorderIntent(), createSoundRecorderIntent());
        chooser.putExtra(Intent.EXTRA_INTENT, i);
        return chooser;
    }

private Intent createChooserIntent(Intent... intents) {
        Intent chooser = new Intent(Intent.ACTION_CHOOSER);
        chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, intents);
        chooser.putExtra(Intent.EXTRA_TITLE, "选择文件");
        return chooser;
    }

private Intent createCameraIntent() {
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File externalDataDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        File cameraDataDir = new File(externalDataDir.getAbsolutePath() + File.separator + "e-photos");
        cameraDataDir.mkdirs();
        mPhotoFilePath = cameraDataDir.getAbsolutePath() + File.separator + System.currentTimeMillis() + ".jpg";
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mPhotoFilePath)));
        return cameraIntent;
    }

private Intent createCamcorderIntent() {
        Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        File externalDataDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        File cameraDataDir = new File(externalDataDir.getAbsolutePath() + File.separator + "e-videos");
        cameraDataDir.mkdirs();
        mVideoFilePath = cameraDataDir.getAbsolutePath() + File.separator + System.currentTimeMillis() + ".3gp";
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mVideoFilePath)));
        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); // set the video
        return intent;
    }

private Intent createSoundRecorderIntent() {
        Intent intent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
        File externalDataDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        File cameraDataDir = new File(externalDataDir.getAbsolutePath() + File.separator + "e-voices");
        cameraDataDir.mkdirs();
        mVoiceFilePath = cameraDataDir.getAbsolutePath() + File.separator + System.currentTimeMillis() + ".amr";
        return intent;
    }

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == FILECHOOSER_RESULTCODE) {
            Uri result= data == null || resultCode != RESULT_OK ? null :data.getData();
            if (result == null && data == null && resultCode == Activity.RESULT_OK) {
                File mMediaFile = null;;
                if(new File(mVideoFilePath).exists()){
                    mMediaFile = new File(mVideoFilePath);
                }else if(new File(mPhotoFilePath).exists()){
                    mMediaFile = new File(mPhotoFilePath);
                }else if(new File(mVoiceFilePath).exists()){
                    mMediaFile = new File(mVoiceFilePath);
                }
                if (mMediaFile!=null&&mMediaFile.exists()) {
                    result = Uri.fromFile(mMediaFile);
                    sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, result));
                }
//                result = Uri.fromFile(new File(mCameraFilePath));
            }
            if(result!=null){
                if(!new File(result.getPath()).canRead()){
                    try {
                        MyFile.copyFile(new File(mVoiceFilePath),getContentResolver().openInputStream(result));
                        createUploadFileItem(mVoiceFilePath);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }else {
                    createUploadFileItem(result.getPath());
                }
            }

System.out.println(result);
        }
    }

}

绘制现在文件信息后的Item
复制代码 代码如下:
package com.guotop.elearn.activity.app.yunpan.item;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.Random;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.guotop.base.L;
import com.guotop.base.handler.BaseHandler;
import com.guotop.base.thread.HttpThread;
import com.guotop.base.util.MyFile;
import com.guotop.base.util.MyHashMap;
import com.guotop.elearn.activity.R;
import com.guotop.elearn.activity.app.yunpan.Y;
import com.guotop.elearn.activity.app.yunpan.bean.UploadYunFileInformaction;
import com.guotop.elearn.activity.app.yunpan.thread.UploadYunFileHttpThread;

/**
 *
 *
 * @author: 李杨
 * @time: 2014-4-21下午12:28:33
 */
public class YunPanUploadFileItem implements OnClickListener {

LinearLayout view,parentView;
    String filePath;

private Context context;

private TextView uploadFileProgressText, uploadFileName;
    private ProgressBar uploadFileProgressBar;
    private ImageView uploadFileImg;
    private Button startUploadFileBtn, cancelUploadFileBtn;

private String actionURL;

BaseHandler handler;
    UploadYunFileHttpThread t;
    UploadYunFileInformaction uploadYunFileInformaction ;

public YunPanUploadFileItem(Context context,LinearLayout parentView, String filePath,String actionURL) {
        this.parentView = parentView;
        this.actionURL = actionURL;
        this.context = context;

File file = new File(filePath);

this.view = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.activity_yunpan_uploadfile_item, null);

//        this.view = view;
        this.filePath = filePath;

uploadFileProgressText = (TextView) view.findViewById(R.id.uploadFileProgressText);
        uploadFileName = (TextView) view.findViewById(R.id.uploadFileName);

uploadFileProgressBar = (ProgressBar) view.findViewById(R.id.uploadFileProgressBar);
        uploadFileImg = (ImageView) view.findViewById(R.id.uploadFileImg);

cancelUploadFileBtn = (Button) view.findViewById(R.id.cancelUploadFileBtn);
        startUploadFileBtn = (Button) view.findViewById(R.id.startUploadFileBtn);

uploadFileName.setText(file.getName()+"   大小"+MyFile.formetFileSize(file.getPath()));
        uploadFileImg.setImageResource(MyFile.getFileIcon(file));

startUploadFileBtn.setOnClickListener(this);
        cancelUploadFileBtn.setOnClickListener(this);
        parentView.addView(view);

uploadYunFileInformaction = new UploadYunFileInformaction(filePath);
        myHandler = new MyHandler(Looper.myLooper(), this);
        uploadYunFileInformaction.setNotificationId(new Random().nextInt(10000));
        uploadYunFileInformaction.setActionURL(actionURL);
        t = new UploadYunFileHttpThread(myHandler, uploadYunFileInformaction);
        uploads.put(uploadYunFileInformaction.getNotificationId(), t);

}

@Override
    public void onClick(View v) {
        if (v.getId() == R.id.startUploadFileBtn) {
            downFile(t);
            startUploadFileBtn.setClickable(false);
        }else if(v.getId()==R.id.cancelUploadFileBtn){
            if(t.isStart){
                new AlertDialog.Builder(context).setTitle("系统提示!").setMessage("该文件正在上传确定要强制停止?")
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                            }
                        }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                t.interrupt();
                                parentView.removeView(view);
                                uploads.removeKey(uploadYunFileInformaction.getNotificationId());
                                System.gc();
                            }
                        }).show();
            }else {

parentView.removeView(view);
                uploads.removeKey(uploadYunFileInformaction.getNotificationId());
            }
        }
    }

public static MyHashMap<Integer, UploadYunFileHttpThread> uploads = new MyHashMap<Integer, UploadYunFileHttpThread>();

private MyHandler myHandler;

public IBinder onBind(Intent intent) {
        return null;
    }

// 下载更新文件
    private void downFile(UploadYunFileHttpThread t) {
        int len = 3;

if (t != null && uploads.size() <= len) {
            if (!t.isStart) {
                t.start();
            }
        } else if (t == null && uploads.size() >= len) {
            t = uploads.get(len - 1);
            if (!t.isStart) {
                t.start();
            }
        }
    }

/* 事件处理类 */
    class MyHandler extends BaseHandler {
        private WeakReference<YunPanUploadFileItem> bdfs;

public MyHandler(Looper looper, YunPanUploadFileItem yunPanUploadFileItem) {
            super(looper);
            this.bdfs = new WeakReference<YunPanUploadFileItem>(yunPanUploadFileItem);
        }

@Override
        public void handleMessage(Message msg) {
            YunPanUploadFileItem bdfs = this.bdfs.get();
            if (bdfs == null) {
                return;
            }
            if (msg != null) {
                switch (msg.what) {
                case 0:
                    Toast.makeText(L.livingActivity, msg.obj.toString(), Toast.LENGTH_SHORT).show();
                    break;
                case L.dowloadStart:
                    break;
                case L.dowloadFinish:
                    // 下载完成后清除所有下载信息,执行安装提示
                    try {
                        uploads.removeKey(msg.getData().getInt("notificationId"));

bdfs.uploadFileProgressText.setText("上传完成");
                        bdfs.uploadFileProgressBar.setMax(100);
                        bdfs.uploadFileProgressBar.setProgress(100);
                        startUploadFileBtn.setClickable(false);

} catch (Exception e) {

}
                    bdfs.downFile(null);
                    break;
                case L.dowloadPercentage:
                    // 更新状态栏上的下载进度信息
                    bdfs.uploadFileProgressText.setText("总共:"+MyFile.formetFileSize(msg.getData().getInt("fileSize"))+ "/" + MyFile.formetFileSize(msg.getData().getInt("finishFileSize")) + "  已上传"
                            + msg.getData().getInt("percentage") + "%");
                    bdfs.uploadFileProgressBar.setMax(100);
                    bdfs.uploadFileProgressBar.setProgress(msg.getData().getInt("percentage"));
                    break;
                case 4:
                    // bdfs.nm.cancel(msg.getData().getInt("notificationId"));
                    break;
                }

}
        }
    }

}

用来上传文件的线程

复制代码 代码如下:
package com.guotop.elearn.activity.app.yunpan.thread;

import java.net.SocketException;

import com.guotop.base.L;
import com.guotop.base.Util;
import com.guotop.base.handler.BaseHandler;
import com.guotop.base.thread.HttpThread;
import com.guotop.elearn.activity.app.yunpan.bean.UploadYunFileInformaction;
import com.guotop.elearn.activity.app.yunpan.util.YunPanUploadFile;
import com.guotop.elearn.activity.app.yunpan.util.YunPanUploadFileHttpInterface;

/**
 *
 * 下载云服务器上的文件
 *
 *
 *@author: 李杨
 *@time: 2014-4-11下午6:06:53
 */
public class UploadYunFileHttpThread extends HttpThread{

@SuppressWarnings("unused")
    private UploadYunFileInformaction uploadYunFileInformaction;

public boolean isStart=false;

public static int RECONNECT = 1000002;
    public static int CAN_NOT_RECONNECT = 1000003;

YunPanUploadFile yunPanUploadFile;

public UploadYunFileHttpThread(){

}

public UploadYunFileHttpThread(BaseHandler handler,UploadYunFileInformaction dowFile){
        this.uploadYunFileInformaction=dowFile;
        this.handler=handler;
    }

int fileSize,finishFileSize,percentage;

private boolean isUpdate = true;
    public void run() {
        isStart=true;//是启动了
        new HttpThread(handler){
            public void run() {
                while (isUpdate) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {

}
                    if(finishFileSize!=0&&fileSize!=0){
                        msg = handler.obtainMessage();
                        if(percentage>=100){
//                            msg.what=L.dowloadFinish;
//                            msg.setData(bundle);
//                            handler.sendMessage(msg);

时间: 2024-07-31 21:26:33

android文件上传示例分享(android图片上传)的相关文章

android文件上传示例分享(android图片上传)_Android

主要思路是调用系统文件管理器或者其他媒体采集资源来获取要上传的文件,然后将文件的上传进度实时展示到进度条中. 主Activity 复制代码 代码如下: package com.guotop.elearn.activity.app.yunpan.activity; import java.io.File;import java.io.FileNotFoundException;import java.io.IOException; import android.app.Activity;impor

Android中使用七牛云存储进行图片上传下载的实例代码

Android开发中的图片存储本来就是比较耗时耗地的事情,而使用第三方的七牛云,便可以很好的解决这些后顾之忧,最近我也是在学习七牛的SDK,将使用过程在这记录下来,方便以后使用. 先说一下七牛云的存储原理,上面这幅图片是官方给出的原理图,表述当然比较清晰了. 可以看出,要进行图片上传的话可以分为五大步: 1. 客户端用户登录到APP的账号系统里面: 2. 客户端上传文件之前,需要向业务服务器申请七牛的上传凭证,这个凭证由业务服务器使用七牛提供的服务端SDK生成: 3. 客户端使用七牛提供的客户端

Android中使用GridView实现仿微信图片上传功能(附源代码)

由于工作要求最近在使用GridView完成图片的批量上传功能,我的例子当中包含仿微信图片上传.拍照.本地选择.相片裁剪等功能,如果有需要的朋友可以看一下,希望我的实际经验能对您有所帮助. 直接上图,下面的图片就是点击"加号"后弹出的对话框,通过对话框可以根据自己需求进行相片选择. 项目结构: 下面直接上代码. 整体的布局文件activity_main.xml <LinearLayout xmlns:android="http://schemas.android.com/

ThinkPHP示例中心添加图片上传示例

ThinkPHP新添加了3.1版本的图片上传示例. 新版的上传类内部做了一些调整,实例化的参数也有所改变,目的是为了更加明确化. ThinkPHP示例之图片上传,包括图片上传.数据库保存.缩略图生成以及图片水印功能演示.首先需要下载框架核心,然后把示例解压到Web根目录下面,并修改入口文件中的框架入口文件的位置.导入示例目录下面的data.sql文件到你的数据库,或者执行SQL: CREATE&http://www.aliyun.com/zixun/aggregation/37954.html&q

位置-求组android怎么通过屏幕上的坐标点换算成图片上的坐标点

问题描述 求组android怎么通过屏幕上的坐标点换算成图片上的坐标点 简单说:界面上有一张图片,想实现点击图片不同位置响应不同事件,所以就想说点击屏幕可以获得点击的坐标,然后通过得到的点的坐标然后换算成该点在图片上的坐标.但是把屏幕上得到的点的坐标换算成该点在图片上的坐标值要怎么换算呢?网上搜过说得到图片坐标,分辨率,点击点的坐标就可以换算成该点在图片上的坐标,但是没说怎么换算的问题...求大神解答 解决方案 方法网上其实都说到了,只是具体的要根据你图片显示的布局才能确定. 你要知道: 1 图

PS图片上怎么画虚线 PS图片上画虚线(图文)

  PS图片上怎么画虚线   PS图片上画虚线(图文)            完成效果: 下面是具体的制作方法介绍: 步骤一:新建一个随意大小的空白文档,为了视觉效果,建议在新建的时候选用白色为背景颜色.我新建的为300x300px 步骤二(重要):背景图层上面,新建一个透明图层. 步骤三:矩形选框工具,建立任意大小的矩形. 步骤四:1.画笔工具,设画笔大小为5~8px之间,硬度为100%. 2.画笔窗口,调节间距在140%左右. 步骤五:按住键盘shift键并单击矩形选框的四个顶点,得到如下图

android实现widget时钟示例分享_Android

一.在 AndroidManifest.xml文件中配置Widgets: 复制代码 代码如下: <manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.widget"    android:versionCode="1"    android:versionName="1.0" >   

android实现widget时钟示例分享

一.在 AndroidManifest.xml文件中配置Widgets: 复制代码 代码如下:<manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.widget"    android:versionCode="1"    android:versionName="1.0" >   

asp.net文件上传示例分享_实用技巧

方法一:用Web控件FileUpload,上传到网站根目录. Test.aspx关键代码: 复制代码 代码如下: <form id="form1" runat="server"><asp:FileUpload ID="FileUpload1" runat="server" /><asp:Button ID="Button1" runat="server" T