我正在尝试使用预签名的URL将文件上传到AWS s3。这是我的 代码:
public void uploadImage(MultipartFile file) {
Date expiration = new Date(System.currentTimeMillis() + 1000 * 60 * 60);
// Generate the pre-signed URL.
System.out.println("Generating pre-signed URL.");
GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucketName, this
.generateFileName(file))
.withMethod(HttpMethod.PUT)
.withExpiration(expiration);
URL url = s3client.generatePresignedUrl(generatePresignedUrlRequest);
api.uploadFileTos3bucket(file, url);
}
public Response uploadFileTos3bucket(MultipartFile file, URL url) {
WebTarget t = createRequest(url);
Response r = this.getResponse("uploadImageToS3", t, file);
return r;
}
private File convertMultiPartToFile(MultipartFile file) throws IOException {
File convFile = new File(file.getOriginalFilename());
FileOutputStream fos = new FileOutputStream(convFile);
fos.write(file.getBytes());
fos.close();
return convFile;
}
protected Response getResponse(String apiName, WebTarget t, MultipartFile file) {
MultiPart fileEntity = null;
try {
File fileToUpload = this.convertMultiPartToFile(file);
fileEntity = new MultiPart();
if (fileToUpload != null) {
fileEntity.bodyPart(new FileDataBodyPart("file", fileToUpload,
MediaType.APPLICATION_OCTET_STREAM_TYPE));
}
} catch (IOException e) {
e.printStackTrace();
}
Response r = t.request().put(Entity.entity(fileEntity, fileEntity.getMediaType()));
if (r.getStatus() == 200) {
return r;
} else {
log.error("API error: " + r.readEntity(String.class));
throw new ServerRuntimeException("Failed to call " + apiName + " API due to status " + r.getStatus());
}
}
// common helper for creating a base request with standard fields set
protected WebTarget createRequest(URL url) {
try {
return CLIENT.target(url.toURI()).register(MultiPartFeature.class);
} catch (URISyntaxException e) {
throw new ServerRuntimeException("Failed to transform url " + url.toString() + " to uri");
}
}
我注意到,每次上传文件后,都会在我的应用程序根文件夹下创建一个相同的副本。如何防止应用程序中的文件复制? 这是调用预签名URL上载文件的正确方法吗?