gpt4 book ai didi

java - Spring 休息-发布文件

转载 作者:搜寻专家 更新时间:2023-11-01 01:25:54 24 4
gpt4 key购买 nike

我有以下代码用于将文件发布到服务并且工作正常。我遇到的唯一问题是,我必须编写一个临时文件来获取 FileSystemResource 以使用 restTemplate 发布对象

有没有办法修改下面的代码,这样我就不必编写临时文件了?

    public String postNewIcon2(Integer fileId, MultipartFile multiPartfile) {
LOG.info("Entered postNewIcon");

Map<String, Object> params = getParamsWithAppKey();
params.put("fileId", fileId);

String result = null;
File tempFile = null;
try {

String originalFileNameAndExtension = multiPartfile.getOriginalFilename();

String tempFileName = "c:\\temp\\image";
String tempFileExtensionPlusDot = ".png";

tempFile = File.createTempFile(tempFileName, tempFileExtensionPlusDot);
multiPartfile.transferTo(tempFile);
FileSystemResource fileSystemResource = new FileSystemResource(tempFile);

// URL Parameters
MultiValueMap<String, Object> parts = new LinkedMultiValueMap<String, Object>();
parts.add("file", fileSystemResource);

// Post
result = restTemplate.postForObject(getFullURLAppKey(URL_POST_NEW_ICON), parts, String.class, params);

} catch (RestClientException restClientException) {
System.out.println(restClientException);
} catch (IOException ioException) {
System.out.println(ioException);
} finally {
if (tempFile != null) {
boolean deleteTempFileResult = tempFile.delete();
LOG.info("deleteTempFileResult: {}", deleteTempFileResult);
}
}
return result;
}

谢谢

最佳答案

在 Kresimir Nesek 和此链接的帮助下回答 Sending Multipart File as POST parameters with RestTemplate requests

下面的代码起到了作用——现在不需要临时文件了

    MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
final String filename="somefile.txt";
map.add("name", filename);
map.add("filename", filename);
ByteArrayResource contentsAsResource = new ByteArrayResource(content.getBytes("UTF-8")){
@Override
public String getFilename(){
return filename;
}
};
map.add("file", contentsAsResource);
String result = restTemplate.postForObject(urlForFacade, map, String.class);

关于java - Spring 休息-发布文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28246736/

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