实现多文件的上传,基于标准的http来实现。
1.多文件上传MyUploader类的实现:
/** * * 同步上传多个文件 * 基于标准的http实现,需要在非UI线程中调用,以免阻塞UI。 * */ public class MyUploader { private static final String TAG = "MyUploader"; // ////////////////////同步上传多个文件///////// /** * 同步上传File * * @param Url * @param fullFileName * : 全路径,ex. /sdcard/f/yh.jpg * @param fileName * : file name, ex. yh.jpg * @return 服务器的响应结果(字符串形式) */ public String MyUploadMultiFileSync(String Url, ListfileList, Map params) { String reulstCode = ""; String end = "\r\n"; String twoHyphens = "--"; String boundary = "--------boundary"; try { URL url = new URL(actionUrl); HttpURLConnection con = (HttpURLConnection) url.openConnection(); // 允许Input、Output,不使用Cache con.setDoInput(true); con.setDoOutput(true); con.setUseCaches(false); // 设置传送的method=POST con.setRequestMethod("POST"); // setRequestProperty con.setRequestProperty("Connection", "Keep-Alive"); con.setRequestProperty("Charset", "UTF-8"); // con.setRequestProperty("Content-Type", // "application/x-www-form-urlencoded"); con.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); StringBuffer s = new StringBuffer(); // 设置DataOutputStream DataOutputStream dos = new DataOutputStream(con.getOutputStream()); for (int i = 0; i
2. 调用方法:
由于MyUploader的MyUploadMultiFileSync本身是同步的函数请求,所以,这个函数需要在非UI线程中执行。本例采用Thread+Handler的方式来进行说明。
下面是activity的主要代码,功能是将cache目录中的的jpg文件上传到指定的服务器:
public void uploadThreadTest() { new Thread(new Runnable() { @Override public void run() { try { upload(); } catch (Exception e) { e.printStackTrace(); } } }).start(); } private void upload() { String url = "https://httpbin.org/post"; ListfileList = getCacheFiles(); if (fileList == null) { myHandler.sendEmptyMessage(-1); }else { MyUploader myUpload = new MyUploader(); //同步请求,直接返回结果,根据结果来判断是否成功。 String reulstCode = myUpload.MyUploadMultiFileSync(url, fileList, null); Log.i(TAG, "upload reulstCode: " + reulstCode); myHandler.sendEmptyMessage(0); } } private List getCacheFiles() { List fileList = new ArrayList (); File catchPath = mContext.getCacheDir(); if (catchPath!=null && catchPath.isDirectory()) { File[] files = catchPath.listFiles(); if (files == null || files.length<1) { return null; } for (int i = 0; i
3 项目demo代码地址:https://github.com/ranke/HttpAsyncTest
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。