作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试将我的服务器上的文件上传到另一台服务器。在做这件事的同时我收到此错误:已解决[org.springframework.web.multipart.support.MissingServletRequestPartException:所需的请求部分"file"不存在]
我已将"file"键放入体内。我无法弄清楚为什么会发生这种情况。
上传服务器:
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
MultiValueMap<String, Object> body
= new LinkedMultiValueMap<>();
body.add("file", Paths.get("pathToFile").toFile());
HttpEntity<MultiValueMap<String, Object>> requestEntity
= new HttpEntity<>(body, headers);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate
.postForEntity(url, requestEntity, String.class);
我们上传到的服务器:
@RequestMapping(value = "/api", method = RequestMethod.POST, consumes = MediaType.ALL_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ResponseDTO> solveUsingJar(@RequestParam("file") MultipartFile file) {
}
最佳答案
我分享了一些代码,用于将一台服务器上的文件上传到另一台服务器。
第 1 步:在 Server-1 中上传文件:
@PostMapping("/upload/profile")
public UploadFileResponse uploadProfileImg(@RequestPart("file") MultipartFile file)
{
return fileService.uploadProfileImg(file);
}
第 2 步:使用 RestTemplate 在 Server-2 中上传该文件。
public String upload(MultipartFile file) throws IOException
{
ResponseEntity<UploadFileResponse> response = null;
try
{
File convFile = new File(file.getOriginalFilename());
convFile.createNewFile();
FileOutputStream fos = new FileOutputStream(convFile);
fos.write(file.getBytes());
fos.close();
LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
String uploadURI = KeyConstant.FILE_UPLOAD_API_URI+"/file"; // Server-2(file Directory) FILE_UPLOAD_API_URI : http://27.34.2.33:28181/upload/file
map.add("file", new FileSystemResource(convFile));
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity = new HttpEntity<>(map, headers);
RestTemplate restTemplate = new RestTemplate();
response = restTemplate.exchange(uploadURI, HttpMethod.POST, requestEntity, UploadFileResponse.class);
}
catch(Exception e) {e.printStackTrace();}
return response.getBody();
}
第 3 步:Server-2 文件上传休息 Controller :
@PostMapping("/upload/file")
public UploadFileResponse uploadFileByDirectory(@RequestPart(value = "file") MultipartFile file)
{
return this.amazonClient.uploadFilebyDirectory(KeyConstant.AMAZON_S3_PATH, file);
}
关于java - 无法将文件从一个服务器上传到另一个服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61041606/
我有以下正则表达式 /[a-zA-Z0-9_-]/ 当字符串只包含从 a 到z 大小写、数字、_ 和 -。 我的代码有什么问题? 能否请您向我提供一个简短的解释和有关如何修复它的代码示例? //var
我是一名优秀的程序员,十分优秀!