本文要用java.net.HttpURLConnection来实现多个文件上传
1. 研究 form 表单到底封装了什么样的信息发送到servlet。
假如我参数写的内容是hello word,然后二个文件是二个简单的txt文件,form提交的信息为:
-----------------------------7da2e536604c8
Content-Disposition: form-data; name="username"
hello word
-----------------------------7da2e536604c8
Content-Disposition: form-data; name="file1"; filename="D:/haha.txt"
Content-Type: text/plain
haha
hahaha
-----------------------------7da2e536604c8
Content-Disposition: form-data; name="file2"; filename="D:/huhu.txt"
Content-Type: text/plain
messi
huhu
-----------------------------7da2e536604c8--
研究下规律发现有如下几点特征
1.第一行是“ -----------------------------7d92221b604bc ”作为分隔符,然后是“ /r/n ” 回车换行符。 这个7d92221b604bc 分隔符浏览器是随机生成的。
2.第二行是Content-Disposition: form-data; name="file2"; filename="D:/huhu.txt";name=对应input的name值,filename对应要上传的文件名(包括路径在内),
3.第三行如果是文件就有Content-Type: text/plain;这里上传的是txt文件所以是text/plain,如果上穿的是jpg图片的话就是image/jpg了,可以自己试试看看。
然后就是回车换行符。
4.在下就是文件或参数的内容或值了。如:hello word。
5.最后一行是-----------------------------7da2e536604c8--,注意最后多了二个--;
有了这些就可以使用HttpURLConnection来实现上传文件功能了
public class FileUpload extends AsyncTask {
public static final String TAG = "FileUpload";
String actionUrl;
Map<String, String> params;
Map<String, File> files;
UploadListener listener;
public interface UploadListener {
public void onUploadEnd(boolean success,String object);
}
public FileUpload(String actionUrl, Map<String, String> params,Map<String, File> files,UploadListener listener) {
Log.i(TAG,"upload!");
this.actionUrl = actionUrl;
this.params = params;
this.files = files;
this.listener = listener;
}
@Override
protected String doInBackground(Object... arg0) {
String reslut = null;
try {
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);
// 首先组拼文本类型的参数
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)
// for (Map.Entry<String, File> file : files.entrySet()) {
for (String key : files.keySet()) {
StringBuilder sb1 = new StringBuilder();
sb1.append(PREFIX);
sb1.append(BOUNDARY);
sb1.append(LINEND);
sb1.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + key + "\"" + LINEND);
sb1.append("Content-Type: multipart/form-data; charset=" + CHARSET + LINEND);
sb1.append(LINEND);
outStream.write(sb1.toString().getBytes());
File valuefile = files.get(key);
InputStream is = new FileInputStream(valuefile);
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();
// 得到响应码
// success = conn.getResponseCode()==200;
InputStream in = conn.getInputStream();
InputStreamReader isReader = new InputStreamReader(in);
BufferedReader bufReader = new BufferedReader(isReader);
String line = null;
reslut = "";
while ((line = bufReader.readLine()) != null)
reslut += line;
outStream.close();
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return reslut;
}
@Override
protected void onPreExecute() {
//onPreExecute方法用于在执行后台任务前做一些UI操作
Log.i(TAG, "onPreExecute() called");
}
@Override
protected void onCancelled() {
//取消操作
Log.i(TAG, "onCancelled() called");
if (listener!=null) {
listener.onUploadEnd(false, null);
}
}
@Override
protected void onPostExecute(Object result) {
//onPostExecute方法用于在执行完后台任务后更新UI,显示结果
Log.i(TAG, "onPostExecute(Result result) called");
if (listener!=null) {
if (result==null) {
listener.onUploadEnd(false, null);
} else {
listener.onUploadEnd(true, result.toString());
}
}
}
@Override
protected void onProgressUpdate(Object... values) {
//onProgressUpdate方法用于更新进度信息
Log.i(TAG, "onProgressUpdate() called");
}
}
本文分析部分来源:http://blog.youkuaiyun.com/skyer_lei/article/details/6106709,代码由本人编写,转发请注明,谢谢!