gpt4 book ai didi

java - 无法将文件从一个服务器上传到另一个服务器

转载 作者:行者123 更新时间:2023-12-01 17:35:55 25 4
gpt4 key购买 nike

我正在尝试将我的服务器上的文件上传到另一台服务器。在做这件事的同时我收到此错误:已解决[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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com