【发布时间】:2015-01-31 00:16:17
【问题描述】:
我有以下代码用于将文件发布到服务,它工作正常。 我唯一的问题是,我必须编写一个临时文件来获取 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;
}
谢谢
【问题讨论】:
-
我不确定这是否可行,但您可以尝试使用
ByteArrayResource并发布它而不是FileSystemResource。ByteArrayResource r = new ByteArrayResource(multiPartfile.getBytes()) -
感谢 Kresimir - 在此链接的帮助下成功了:stackoverflow.com/questions/4118670/…
标签: java spring spring-mvc