环境 jdk1.8 ide:eclipse 框架:spring 4.3.4 mybatis3.3.4
利用纯java后台实现post提交数据并上传文件
模拟post部分
/**
*
* @description 模拟post提交
* @version 1.0
* @author 张尧
* @update 2017年7月7日 上午9:19:07
*/
public static void uploads(){
String boundary = "----------"+ System.currentTimeMillis();
String url = "http://localhost/compoundLibraryController/savecompoundLibrarys";
OutputStream out = null;
//设置表单域key相当于input的name属性,value相当于input的value属性
Map textMap = new HashMap();
textMap.put("compoundCatalogNo", "cs-1234");
textMap.put("compoundTitle", "阿德干啥的身高多少");
textMap.put("compoundLibraryName", "oldDriver");
try {
URL u = new URL(url);
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
// 指定流的大小,当内容达到这个值的时候就把流输出
conn.setChunkedStreamingMode(10240);
out = new DataOutputStream(conn.getOutputStream());
byte[] end_data = ("\r\n--" + boundary + "--\r\n").getBytes();// 定义最后数据分隔线
//定义多个要上传的文件
List list = new ArrayList();
list.add("D:/HY-11109.pdf");
list.add("D:/12.jpg");
//声明并初始化表单域所需的信息
StringBuilder sb = new StringBuilder();
sb.append("--");
sb.append(boundary);
// 2 写入内容
// 2.1 处理普通表单域(即形如key = value对)的POST请求
for (String key : textMap.keySet()) {
sb.append("\r\n");
sb.append("Content-Disposition: form-data; name=\"").append(key + "\"");
sb.append("\r\n\r\n");
sb.append(textMap.get(key)).append("\r\n").append("--").append(boundary);
}
out.write(sb.toString().getBytes("UTF-8"));
//上传文件
int leng = list.size();
for (int i = 0; i < leng; i++) {
String fname = list.get(i);
File file = new File(fname);
sb = new StringBuilder();
sb.append("--");
sb.append(boundary);
sb.append("\r\n");
sb.append("Content-Disposition: form-data;name=\"files"+i+"\";filename=\"" + file.getName() + "\"\r\n");
sb.append("Content-Type:application/octet-stream\r\n\r\n");
out.write(sb.toString().getBytes());
DataInputStream in = new DataInputStream(new FileInputStream(file));
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
out.write("\r\n".getBytes()); // 多个文件时,二个文件之间加入这个
in.close();
}
out.write((boundary+"--\r\n").getBytes("UTF-8"));
out.write(end_data);
// 定义BufferedReader输入流来读取URL的响应
BufferedReader reader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
System.out.println("发送POST请求出现异常!" + e);
e.printStackTrace();
}finally{
try {
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
服务端
Controller
@RequestMapping(value="savecompoundLibrarys")
@ResponseBody
public String saveCompoundLibrarys(HttpServletRequest request,CompoundLibraryExt compoundLibraryExt){
String status = "Null error";
//将当前上下文初始化给 CommonsMutipartResolver (多部分解析器)
if(compoundLibraryExt.getCompoundCatalogNo()==null){
return status;
}
String message = compoundLibraryExt.getCompoundCatalogNo();
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
try {
if(multipartResolver.isMultipart(request)){
String path = request.getSession().getServletContext().getRealPath("/liberResoult/")+message+"/";
File dirfile= new File(path);
if(!dirfile.exists()){
dirfile.mkdir();
}else{
dirfile.delete();
dirfile.mkdir();
}
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
Iterator iter = multiRequest.getFileNames();
System.out.println(multiRequest.getFileNames());
while(iter.hasNext()){
MultipartFile file = multiRequest.getFile(iter.next().toString());
if(file!=null){
String filePath = path+"/"+file.getOriginalFilename();
file.transferTo(new File(filePath));
}
}
}
} catch (IllegalStateException e) {
status = message+" IllegalStateException";
e.printStackTrace();
} catch (IOException e) {
status = message+" Io流异常";
e.printStackTrace();
}
return status;
}
springMvc配置部分
以下两个都可以使用第一个是spirng默认配置第二个是我为了监控上传进度重写的上传处理器