Android开发中Post方式上传文件(头像之类的)

编程入门 行业动态 更新时间:2024-10-06 20:36:54

Android开发中Post方式<a href=https://www.elefans.com/category/jswz/34/1770844.html style=上传文件(头像之类的)"/>

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方式上传文件(头像之类的)

本文发布于:2023-07-04 09:20:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1022303.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:上传文件   头像   方式   Android   Post

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!