在web开发中上传文件比较简单,一个普通的post表单再加上文件类型的标签就可以完成,上传的这些工作都是交给浏览器完成。但是在客户端上传文件时就需要自己写http上传相关的参数。
......
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryMHzissskK7K82uyt
------WebKitFormBoundaryMHzissskK7K82uyt
Content-Disposition: form-data; name="CLIENT_NO"
123344
------WebKitFormBoundaryMHzissskK7K82uyt
Content-Disposition: form-data; name="file"; filename="mdAndroid.json"
Content-Type: application/json
------WebKitFormBoundaryMHzissskK7K82uyt--
private String prefix = "--";
private String boundary = CryptoUtil.genRandomKey();
private String endLine = "\r\n";
URL url = new URL(uploadUrl);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setChunkedStreamingMode(128 * 1024); //128k
//允许输入输出流
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setUseCaches(false);
//设置请求头信息
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
httpURLConnection.setRequestProperty("Charset", "UTF-8");
httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
DataOutputStream dos = new DataOutputStream(httpURLConnection.getOutputStream());
dos.writeBytes(prefix + boundary + endLine);
dos.writeBytes("Content-Disposition: form-data; name=\"CLIENT_NO\"" + endLine + endLine);
dos.writeBytes("8623732" + endLine);
dos.writeBytes(prefix + boundary + endLine);
dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"mdAndroid.json\"" + endLine);
dos.writeBytes("Content-Type: application/json" + endLine + endLine);
dos.write(fileToByte("mdAndroid.json"));
dos.writeBytes(endLine);
dos.writeBytes(prefix + boundary + prefix + endLine);
dos.flush();
InputStream is = httpURLConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is, "utf-8");
BufferedReader br = new BufferedReader(isr);
String result = br.readLine();
dos.close();
is.close();
RequestParams params = new RequestParams();
params.put("CUSTOMER_NO", "8372721");
params.put("android", fileToStream("mdAndroid.json"), "mdAndroid.json");
AsyncHttpClient client = new AsyncHttpClient();
client.post(url, params, new APPResponseHandler() {
@Override
public void onSuccess(Object result) {
Log.i("sfj", "result===="+result);
}
@Override
public void onFailure(String errorCode, String errorMsg) {
Log.i("sfj", errorCode + errorMsg);
}
});
使用SpringMVC框架,全局spring-servlet.xml配置项
接收请求,文件保存操作,简化步骤:
1、转换请求为多文件请求,也可直接在方法参数里面直接接收MultipartHttpServletRequest参数
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request
2、获取键值对参数:
request.getParameter("参数名")
3、获取文件数据集合:
request.getFileMap()
4、遍历集合,使用MultipartFile自带的方法进行文件保存
multiFile.transferTo(new File("文件保存路径"))