第一步:在Spring配置中添加以下内容
class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
p:defaultEncoding="UTF-8" p:maxUploadSize="540000000" p:uploadTempDir="fileUpload/temp">
第二步:编写上传Spring接口
/*** 上传专报
*
*@paramtypeId
*@paramuserId
*@paramfile
*@return
*/@ResponseBody
@RequestMapping(params= "uploadDoc")public Return uploadDoc(@RequestParam(value = "file", required = true) MultipartFile file,String newFileName) {
Return r= newReturn();
System.out.println(newFileName);try{//3.保存word文件
if (file != null) {//文件存入临时目录
String thisFile=SaveFile.save(file, newFileName);if(thisFile!=null){
r.setE(1);
r.setS("上传专报成功!");
}else{
r.setE(0);
r.setS("上传专报失败!");
}
}
}catch(Exception e) {
e.printStackTrace();
r.setS("系统异常");
}returnr;
}/*** 保存文件到临时目录
*
*@paramfiles
*@param保存文件路径包含文件名称
*@return
*/
public staticString save(MultipartFile files,String newFilePath) {
String fileName=files.getOriginalFilename();if (fileName == null) {return null;
}
File file= newFile(newFilePath);if(!file.exists()){try{
FileOutputStream fop= newFileOutputStream(file);
file.createNewFile();//获取文件字节
byte[] contentInBytes =files.getBytes();
fop.write(contentInBytes);//写入本地
fop.flush();
fop.close();returnnewFilePath;
}catch(FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}
}return null;
}
第三步:编写上传程序
上传程序所需jar:httpclient-4.5.3.jar,httpmime-4.5.3.jar
/*** 上传文件到指定地址URL
*
*@param本地文件
*@param请求接口路径
*@paramnewfilePath 其他参数
*@return是否成功*/
public static booleanuploadFile(String filePath, String urlStr, String newfilePath) {try{
String sTestsetFile=newfilePath;
String sURL= urlStr;//"http://localhost:8080/qxfw/productController.do?uploadDoc";
CloseableHttpClient httpClient=HttpClients.createDefault();
HttpPost uploadFile= newHttpPost(sURL);
MultipartEntityBuilder builder=MultipartEntityBuilder.create();
builder.addTextBody("newFileName", newfilePath, ContentType.TEXT_PLAIN);//把文件加到HTTP的post请求中
File f= newFile(sTestsetFile);
builder.addBinaryBody("file", newFileInputStream(f), ContentType.APPLICATION_OCTET_STREAM, f.getName());
HttpEntity multipart=builder.build();
uploadFile.setEntity(multipart);
CloseableHttpResponse response=httpClient.execute(uploadFile);
HttpEntity responseEntity=response.getEntity();
String sResponse= EntityUtils.toString(responseEntity, "UTF-8");if (sResponse.contains("成功")) {return true;
}else{return false;
}
}catch(Exception e) {//TODO: handle exception
e.printStackTrace();
}return false;
}