java 调用Spring接口上传文件及其他参数填充

 

第一步:在Spring配置中添加以下内容

<!-- 配置MultipartResolver 用于文件上传 使用spring的CommosMultipartResolver -->

<bean id="multipartResolver"

class="org.springframework.web.multipart.commons.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("上传专报成功!");

}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 = files.getOriginalFilename();

if (fileName == null) {

return null;

}

File file = new File(newFilePath);

if(!file.exists()){

try {

FileOutputStream fop = new FileOutputStream(file);

file.createNewFile();

// 获取文件字节

byte[] contentInBytes = files.getBytes();

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;//"http://localhost:8080/qxfw/productController.do?uploadDoc";

CloseableHttpClient httpClient = HttpClients.createDefault();

HttpPost uploadFile = new HttpPost(sURL);

 

MultipartEntityBuilder builder = MultipartEntityBuilder.create();

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 = 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;

}

 

posted @ 2019-09-06 11:26  比较杂的代码工程师  阅读(4167)  评论(0编辑  收藏  举报