gpt4 book ai didi

java - 将多部分文件上传到S3

转载 作者:行者123 更新时间:2023-12-02 08:59:55 25 4
gpt4 key购买 nike

我正在使用 Spring Boot,并且我有一个来自请求的多部分文件,我需要上传到 S3,但 S3 仅支持文件(不支持多部分文件)上传到 S3。如何将多部分文件上传到s3

最佳答案

您可以执行以下操作:

public class S3Utility{
public static String upload(String bucket, String fileName, InputStream inputStream, String contentType, AmazonS3 s3Client, boolean isPublic) {
if (inputStream != null) {
try {
ObjectMetadata meta = new ObjectMetadata();
meta.setContentLength(inputStream.available());
meta.setContentType(contentType);

PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, fileName, inputStream, meta);

if (isPublic) {
putObjectRequest = putObjectRequest.withCannedAcl(CannedAccessControlList.PublicRead);
}

PutObjectResult result = S3Util.getAmazonS3Client(s3Client).putObject(putObjectRequest);
if (result != null) {
return fileName;
}

} catch (Exception e) {
log.error("Error uploading file on S3: ", e);
}
} else {
log.warn("Content InputStream is null. Not Uploading on S3");
}
return null;
}
}


@RestController
public class TestController{


@PostMapping(path = "upload/file", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<String> uploadStampPageImage( @RequestPart(value = "file") MultipartFile imageFile) {

if(Objets.nonNull(file)){
String uploadedFilePath = S3Utility.upload("myBucket","myFile.jpg",file.getInputStream(),file.getContentType(), amazonS3Client, true);
return new ResponseEntity.ok(uploadedFilePath);
}
return new ResponseEntity.failure("Not uploaded");

}

}

}

关于java - 将多部分文件上传到S3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60245130/

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