android文件上传到服务器

代码非原创,fix了bug,完善的还是需要再思量:
/**
* 通过拼接的方式构造请求内容,实现参数传输以及文件传输
* @param actionUrl
* @param params
* @param files
* @return
* @throws IOException
*/
public static String post(String actionUrl, Map<String, String> params,
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");
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);

// 首先组拼文本类型的参数
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINEND);
sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND);
sb.append("Content-Type: text/plain; charset=" + CHARSET+LINEND);
sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
sb.append(LINEND);
sb.append(entry.getValue());
sb.append(LINEND);
}

DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
outStream.write(sb.toString().getBytes());
// 发送文件数据
if(files!=null){
int i = 0;
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"+(i++)+"\"; 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();
InputStream in = null;
if (res == 200) {
in = conn.getInputStream();
int ch;
StringBuilder sb2 = new StringBuilder();
while ((ch = in.read()) != -1) {
sb2.append((char) ch);
}
}
return in == null ? null : in.toString();
}


最简单的PHP测试代码:
if($_FILES){
foreach($_FILES as $v){
copy($v[tmp_name], $v[name]);
}
}


参考自 Android中发送Http请求实例(包括文件上传、servlet接收) ,修复了几个问题:
1 多文件上传 file"+(i++)+"
2 返回的错误

另外还可以看看这个(我没测试) android 文件上传的类--完整 可以直接被调用的

这有一个从协议上分析的,比较牛叉:Android下的应用编程——用HTTP协议实现文件上传功能

原创内容如转载请注明:来自 阿权的书房 <script> //<![cdata[ document.write("<br />本帖地址:<a href=\""+window.location+"\">"+window.location+"</a>"); //]]> </script>
本帖地址:http://www.aslibra.com/blog/post/android-upload-files-to-server.php


http 上传文件的方法

Java代码 收藏代码
1. /**
2. *
3. * sendMultipartDataToHttpServer
4. * 使用post方法请求web服务器,并且当表单数据为:multipart/form-data格式。http请求使用{@link#HTTP_ENCODING}编码<br/>
5. * 返回json数据,支持文件名中文上传和多文件上传,不支持断点上传,要正确编码服务端返回{@link#HTTP_ENCODING}编码<br/>
6. * @param url
7. * @param files 文件表单域
8. * @param fields 非文件表单域
9. * @return JSONObject
10. * @throws Exception
11. * @exception
12. * @since 1.0.0
13. */
14. public static JSONObject sendMultipartDataToHttpServer(URL url,
15. final Map<String, File> files, final Map<String, String> fields,
16. final UsernamePasswordCredentials credentials) throws IOException ,JSONException,Exception{
17. URL myurl = null;
18. String queryString = "";
19. // 其他的表单域
20. if (fields != null) {
21. for (Map.Entry<String, String> entry : fields.entrySet()) {
22. queryString += "&" + URLEncoder.encode(entry.getKey(),HTTP_ENCODING) + "="
23. + URLEncoder.encode(entry.getValue(), HTTP_ENCODING);
24. }
25. }
26. if (!queryString.equals("")) {
27. queryString = queryString.replaceFirst("&", "?");
28. } else {
29. }
30.

31. myurl = new URL(url.getProtocol(), url.getHost(),url.getPort(), url.getPath()
32. + queryString);
33. HttpURLConnection conn = (HttpURLConnection) myurl.openConnection();
34. conn.setConnectTimeout(UPLOAD_REQUEST_TIMEOUT);
35. conn.setRequestMethod(HTTP_METHOD.POST.toString());
36. conn.setDoInput(true);
37. conn.setDoOutput(true);
38. conn.setUseCaches(false);
39.

40. String boundary = "laohuidi_" + java.util.UUID.randomUUID().toString()
41. + "_laohuidi";
42. conn.setRequestProperty(
43. "Accept",
44. "image/gif,image/x-xbitmap,image/jpeg,image/pjpeg,application/vnd.ms-excel,application/vnd.ms-powerpoint,application/msword,application/x-shockwave-flash,application/x-quickviewplus,*/*");
45. conn.setRequestProperty("keep-alive", "300");
46. conn.setRequestProperty(
47. "user-agent",
48. "Mozilla/5.0 (Windows; U; Windows NT 5.2; zh-CN; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6 GTB6");
49. conn.setRequestProperty("accept-language", "zh-cn,zh;q=0.5");
50. conn.setRequestProperty("Connection", "Keep-Alive");
51. conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+ boundary);
52.

53. DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
54. // 乱码问题 可以试下 PrintWriter out = new PrintWriter(new
55. // OutputStreamWriter(connection.getOutputStream(),"utf-8"));
56. dos = new DataOutputStream(conn.getOutputStream());
57. int bytesRead, bytesAvailable, bufferSize;
58. byte[] buffer;
59. int maxBufferSize = IO_BUFFER_SIZE;
60. String tem = "";
61. if(files!=null)
62. for (Map.Entry<String, File> entry : files.entrySet()){
63. // 分隔符开头
64. dos.writeBytes(TWO_HYPHENS + boundary + LINEND);
65. // create a buffer of maximum size
66. FileInputStream fileInputStream = new FileInputStream(entry.getValue());
67. bytesAvailable = fileInputStream.available();
68. bufferSize = Math.min(bytesAvailable, maxBufferSize);
69. buffer = new byte[bufferSize];
70. // read file and write it into form...
71. bytesRead = fileInputStream.read(buffer, 0, bufferSize);
72. tem = entry.getValue().getName();
73. dos.writeBytes("Content-Disposition:form-data;name=\""+entry.getKey()+"\";"+ "filename=\"");
74. dos.writeUTF(tem);// 中文的文件名使用这里
75. dos.writeBytes("\"" + LINEND);
76. dos.writeBytes("Content-Type:image/jpg" + LINEND + LINEND);//类型的判断暂时不处理
77. while (bytesRead > 0) {
78. dos.write(buffer, 0, bufferSize);
79. bytesAvailable = fileInputStream.available();
80. bufferSize = Math.min(bytesAvailable, maxBufferSize);
81. bytesRead = fileInputStream.read(buffer, 0, bufferSize);
82. }
83. // close streams
84. fileInputStream.close();
85. dos.writeBytes(LINEND);
86. }
87. // http 结束符
88. dos.writeBytes(TWO_HYPHENS + boundary + TWO_HYPHENS);
89. dos.writeBytes(LINEND);
90.

91. dos.flush();
92. dos.close();
93. // 返回类型
94. String responseType = conn.getHeaderField("Content-Type");
95. // 正常返回而且必须为json类型
96. if (conn.getResponseCode() == HttpURLConnection.HTTP_OK
97. && responseType != null
98. && responseType.indexOf(HTTP_JSON_TYPE) >= 0) {
99. responseType = (convertStreamToString(conn.getInputStream()));
100.

101. } else {
102. responseType = "{}";
103. }
104. try{conn.disconnect();}catch(Exception e){}
105. return new JSONObject(responseType);
106. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值