基于標(biāo)準(zhǔn)http實(shí)現(xiàn)Android多文件上傳
實(shí)現(xiàn)多文件的上傳,基于標(biāo)準(zhǔn)的http來實(shí)現(xiàn)。
1.多文件上傳MyUploader類的實(shí)現(xiàn):
/** * * 同步上傳多個(gè)文件 * 基于標(biāo)準(zhǔn)的http實(shí)現(xiàn),需要在非UI線程中調(diào)用,以免阻塞UI。 * */ public class MyUploader { private static final String TAG = "MyUploader"; // ////////////////////同步上傳多個(gè)文件///////// /** * 同步上傳File * * @param Url * @param fullFileName * : 全路徑,ex. /sdcard/f/yh.jpg * @param fileName * : file name, ex. yh.jpg * @return 服務(wù)器的響應(yīng)結(jié)果(字符串形式) */ public String MyUploadMultiFileSync(String Url, List<String> fileList, Map<String, String> 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); // 設(shè)置傳送的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(); // 設(shè)置DataOutputStream DataOutputStream dos = new DataOutputStream(con.getOutputStream()); for (int i = 0; i < fileList.size(); i++) { String filePath = fileList.get(i); int endFileIndex = filePath.lastIndexOf("/"); String fileName = filePath.substring(endFileIndex + 1); Log.i(TAG, "filename= " + fileName); // set 頭部 StringBuilder sb = new StringBuilder(); sb.append(twoHyphens); sb.append(boundary); sb.append(end); sb.append("Content-Disposition: form-data; "); sb.append("name=" + "\"" + "upload_file" +i + "\""); sb.append(";filename="); sb.append("\"" + fileName + "\""); sb.append(end); sb.append("Content-Type: "); sb.append("image/jpeg"); sb.append(end); sb.append(end); // 1. write sb dos.writeBytes(sb.toString()); // 取得文件的FileInputStream FileInputStream fis = new FileInputStream(filePath); // 設(shè)置每次寫入1024bytes int bufferSize = 1024; byte[] buffer = new byte[bufferSize]; int length = -1; // 從文件讀取數(shù)據(jù)至緩沖區(qū) while ((length = fis.read(buffer)) != -1) { dos.write(buffer, 0, length); } dos.writeBytes(end); fis.close(); dos.writeBytes(end); dos.writeBytes(end); //dos.writeBytes(end); //dos.flush(); // close streams //fis.close(); } // set 尾部 StringBuilder sb2 = new StringBuilder(); if (params != null && !params.isEmpty()) { for (String key : params.keySet()) { String value = params.get(key); sb2.append(twoHyphens); sb2.append(boundary); sb2.append(end); sb2.append("Content-Disposition: form-data; "); sb2.append("name=" + "\""); sb2.append(key + "\""); sb2.append(end); sb2.append(end); sb2.append(value); sb2.append(end); } } sb2.append(twoHyphens + boundary + end); dos.writeBytes(sb2.toString()); dos.flush(); Log.i(TAG, "sb2:" + sb2.toString()); // 取得Response內(nèi)容 InputStream is = con.getInputStream(); int ch; StringBuffer b = new StringBuffer(); while ((ch = is.read()) != -1) { b.append((char) ch); } reulstCode = b.toString().trim(); // 關(guān)閉 dos.close(); } catch (IOException e) { Log.i(TAG, "IOException: " + e); e.printStackTrace(); } return reulstCode; } }
2. 調(diào)用方法:
由于MyUploader的MyUploadMultiFileSync本身是同步的函數(shù)請(qǐng)求,所以,這個(gè)函數(shù)需要在非UI線程中執(zhí)行。本例采用Thread+Handler的方式來進(jìn)行說明。
下面是activity的主要代碼,功能是將cache目錄中的的jpg文件上傳到指定的服務(wù)器:
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"; List<String> fileList = getCacheFiles(); if (fileList == null) { myHandler.sendEmptyMessage(-1); }else { MyUploader myUpload = new MyUploader(); //同步請(qǐng)求,直接返回結(jié)果,根據(jù)結(jié)果來判斷是否成功。 String reulstCode = myUpload.MyUploadMultiFileSync(url, fileList, null); Log.i(TAG, "upload reulstCode: " + reulstCode); myHandler.sendEmptyMessage(0); } } private List<String> getCacheFiles() { List<String> fileList = new ArrayList<String>(); 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 < files.length; i++) { if (files[i].isFile() && files[i].getAbsolutePath().endsWith(".jpg")) { fileList.add(files[i].getAbsolutePath()); } } return fileList; } return null; } ////////////handler///// private Handler myHandler = new Handler() { @Override public void handleMessage(Message msg) { Log.i(TAG,"handleMessage msg===" + msg); if (msg.what == -1) { Toast.makeText(mContext, "not find file!", Toast.LENGTH_LONG).show(); return; }else { Toast.makeText(mContext, "upload success!", Toast.LENGTH_LONG).show(); } } };
3 項(xiàng)目demo代碼地址:https://github.com/ranke/HttpAsyncTest
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
android常見手動(dòng)和自動(dòng)輪播圖效果
這篇文章主要為大家詳細(xì)介紹了android常見手動(dòng)和自動(dòng)輪播圖效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-11-11Android實(shí)現(xiàn)桌面快捷方式實(shí)例代碼
大家好,本篇文章主要講的是Android實(shí)現(xiàn)桌面快捷方式實(shí)例代碼,感興趣的同學(xué)趕快來看一看吧,對(duì)你有幫助的話記得收藏一下,方便下次瀏覽2021-12-12分享實(shí)現(xiàn)Android圖片選擇的兩種方式
本文給大家分享的是Android選擇圖片的兩種方式的實(shí)現(xiàn)代碼,分別是單張選取和多張批量選取,非常的實(shí)用,有需要的小伙伴可以參考下2016-01-01Android學(xué)習(xí)教程之滑動(dòng)布局(14)
這篇文章主要為大家詳細(xì)介紹了Android學(xué)習(xí)教程之滑動(dòng)布局使用方法,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-11-11