java调⽤Spring接⼝上传⽂件及其他参数填充
第⼀步:在Spring配置中添加以下内容
<!-- 配置MultipartResolver ⽤于⽂件上传使⽤spring的CommosMultipartResolver -->
<bean id="multipartResolver"
class="org.springframework.web.multipartmons.CommonsMultipartResolver"
p:defaultEncoding="UTF-8" p:maxUploadSize="540000000" p:uploadTempDir="fileUpload/temp">
</bean>
第⼆步:编写上传Spring接⼝
/**
* 上传专报
*
* @param typeId
* @param userId
* @param file
* @return
*/
@ResponseBody
@RequestMapping(params = "uploadDoc")
public Return uploadDoc(@RequestParam(value = "file", required = true) MultipartFile file,String newFileName) {
Return r = new Return();
System.out.println(newFileName);
try {
// 3.保存word⽂件
if (file != null) {
// ⽂件存⼊临时⽬录
String thisFile = SaveFile.save(file, newFileName);
if(thisFile!=null){
r.setE(1);
r.setS("上传专报成功!");
spring framework网络系统参数}else{
r.setE(0);
r.setS("上传专报失败!");
}
}
} catch (Exception e) {
e.printStackTrace();
r.setS("系统异常");
}
return r;
}
/**
* 保存⽂件到临时⽬录
*
* @param files
* @param保存⽂件路径包含⽂件名称
* @return
*/
public static String save(MultipartFile files,String newFilePath) {
String fileName = OriginalFilename();
if (fileName == null) {
return null;
}
File file = new File(newFilePath);
if(!ists()){
try {
FileOutputStream fop = new FileOutputStream(file);
// 获取⽂件字节
byte[] contentInBytes = Bytes();
fop.write(contentInBytes);// 写⼊本地
fop.flush();
fop.close();
return newFilePath;
} 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请求接⼝路径
* @param newfilePath 其他参数
* @return是否成功
*/
public static boolean uploadFile(String filePath, String urlStr, String newfilePath) {
try {
String sTestsetFile = newfilePath;
String sURL = urlStr;//"localhost:8080/qxfw/productController.do?uploadDoc";
CloseableHttpClient httpClient = ateDefault();
HttpPost uploadFile = new HttpPost(sURL);
MultipartEntityBuilder builder = ate();
builder.addTextBody("newFileName", newfilePath, ContentType.TEXT_PLAIN);
/
/ 把⽂件加到HTTP的post请求中
File f = new File(sTestsetFile);
builder.addBinaryBody("file", new FileInputStream(f), ContentType.APPLICATION_OCTET_STREAM, f.getName());
HttpEntity multipart = builder.build();
uploadFile.setEntity(multipart);
CloseableHttpResponse response = ute(uploadFile);
HttpEntity responseEntity = Entity();
String sResponse = String(responseEntity, "UTF-8");
if (ains("成功")) {
return true;
} else {
return false;
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return false;
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。