Springboot accepts the form multpartfile and uses httpclient to send a post request to simulate the form upload file (multipart / form data)

Douqu programming 2022-06-23 16:00:32 阅读数:429


Now there's a need , It is the documents submitted from the form , I need to get the file stream in the background and send a request to another server to transfer the file to another server .

The background to use springboot,spring The received file stream is generally converted to MultipartFile type


<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->


// Upload files
@RequestMapping(value = "upload1")
public Object upload1(
@RequestParam(value = "files") MultipartFile[] files, // This receives the file
@RequestParam(value = "file") MultipartFile file, // This receives the file
@RequestParam Map<String,Object> params,
HttpServletRequest request
) {
RetBase ret = new RetBase();
File file2 = null;
String fileName = file.getOriginalFilename();
String prefix = fileName.substring(fileName.lastIndexOf("."));
List<Map<String,Object>> data = new ArrayList<>();
try {
file2 = File.createTempFile(fileName, prefix);
// Copy the uploaded file to the temporary file
//Springboot Use... Directly transferTo The error that the path cannot be found will be reported , You have to make a copy
HashMap param = new HashMap();
// Call the remote sending interface
String content=getRemoteInterfaceStr("upload",param,file2);
// Back to the front desk
ret.setMsg(" Upload successful ");
return ret;
} catch (Exception e) {
ret.setMsg(" Upload failed ");
return ret;
public String getRemoteInterfaceStr1(String actionName,HashMap params,File file1) {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost post = new HttpPost("http://test.cnmaker.top/data.cfrc?action=" + actionName);
try {
// Copy the uploaded file to the temporary file
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
ContentType strContent = ContentType.create("text/plain", Charset.forName("UTF-8"));
builder.addTextBody("attachmentType","certificate" , strContent);
FileBody bin = new FileBody(file1);
builder.addPart("file", bin);
// Transmit text parameters
// builder.addPart("attachmentType",
// new StringBody("certificate", ContentType.create("text/plain", Consts.UTF_8)));
HttpEntity parameterEntity = builder.build();
// Don't make it by yourself header, It will simulate itself , If you specify it yourself, you will report an error
//post.setHeader("Content-type", "multipart/form-data");
CloseableHttpResponse response = httpClient.execute(post, HttpClientContext.create());
String content = EntityUtils.toString(response.getEntity());
// Insert the corresponding table
return content;
} catch (Exception e) {
}finally {
// Complete the above file You need to delete the temporary files generated in the root directory
return null;


版权声明:本文为[Douqu programming]所创,转载请带上原文链接,感谢。 https://qdmana.com/2022/174/202206231526552024.html