Android开发中Post方式上传文件(头像之类的)
生活随笔
收集整理的這篇文章主要介紹了
Android开发中Post方式上传文件(头像之类的)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
/*** 文件上傳* @param actionUrl:上傳接口地址* @param files:需上傳的文件集合* @return* @throws IOException*/
public static String upLoadFilePost(String actionUrl, Map<String, File> files) throws IOException {String BOUNDARY = java.util.UUID.randomUUID().toString();String PREFIX = "--", LINEND = "\r\n";String MULTIPART_FROM_DATA = "multipart/form-data";String CHARSET = "UTF-8";URL uri = new URL(actionUrl);HttpURLConnection conn = (HttpURLConnection) uri.openConnection();conn.setReadTimeout(5 * 1000);conn.setDoInput(true);// 允許輸入conn.setDoOutput(true);// 允許輸出conn.setUseCaches(false);conn.setRequestMethod("POST"); // Post方式conn.setRequestProperty("connection", "keep-alive");conn.setRequestProperty("Charsert", "UTF-8");conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA+ ";boundary=" + BOUNDARY);DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());// 發送文件數據if (files != null)for (Map.Entry<String, File> file : files.entrySet()) {StringBuilder sb1 = new StringBuilder();sb1.append(PREFIX);sb1.append(BOUNDARY);sb1.append(LINEND);sb1.append("Content-Disposition: form-data; name=\"file\"; filename=\""+ file.getKey() + "\"" + LINEND);sb1.append("Content-Type: application/octet-stream; charset="+ CHARSET + LINEND);sb1.append(LINEND);outStream.write(sb1.toString().getBytes());InputStream is = new FileInputStream(file.getValue());byte[] buffer = new byte[1024];int len = 0;while ((len = is.read(buffer)) != -1) {outStream.write(buffer, 0, len);}is.close();outStream.write(LINEND.getBytes());}// 請求結束標志byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();outStream.write(end_data);outStream.flush();// 得到響應碼int res = conn.getResponseCode();if (res == 200) {InputStream in = conn.getInputStream();InputStreamReader isReader = new InputStreamReader(in);BufferedReader bufReader = new BufferedReader(isReader);String line = "";String data = "";while ((line = bufReader.readLine()) != null) {data += line;}outStream.close();conn.disconnect();return data;}outStream.close();conn.disconnect();return "";
}
PS:在子線程中調用。
總結
以上是生活随笔為你收集整理的Android开发中Post方式上传文件(头像之类的)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 《阿尔卑斯》观后感 (r10笔记第44天
- 下一篇: Android Activity