gpt4 book ai didi

java - 文件未上传到 s3 存储桶

转载 作者:行者123 更新时间:2023-11-30 06:25:04 25 4
gpt4 key购买 nike

我正在尝试使用 spring mvc rest api 将文件上传到 aws-s3 存储桶。这是我访问 s3 存储桶的凭据格式

[default]
aws_access_key_id = Access key id
aws_secret_access_key = secret access key

这是我的 Java 代码:

@RestController
public class UploadController {

private static String bucketName= "mp4-upload-1";
private static String keyName= "secret access key";
public static final Logger logger=LogManager.getLogger(UploadController.class);

@RequestMapping(value="/uploadVideo", method = RequestMethod.POST, consumes=MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<String> uploadVideo(@RequestParam("file") MultipartFile file) throws IOException {


AmazonS3 s3client = new AmazonS3Client(new ProfileCredentialsProvider());
try {
System.out.println("Uploading a new object to S3 from a file\n");

InputStream is=file.getInputStream();

s3client.putObject(new PutObjectRequest(bucketName, keyName,is,new ObjectMetadata()).withCannedAcl(CannedAccessControlList.PublicRead));


} catch (AmazonServiceException ase) {
System.out.println("Caught an AmazonServiceException, which " +
"means your request made it " +
"to Amazon S3, but was rejected with an error response" +
" for some reason.");
System.out.println("Error Message: " + ase.getMessage());
System.out.println("HTTP Status Code: " + ase.getStatusCode());
System.out.println("AWS Error Code: " + ase.getErrorCode());
System.out.println("Error Type: " + ase.getErrorType());
System.out.println("Request ID: " + ase.getRequestId());
} catch (AmazonClientException ace) {
System.out.println("Caught an AmazonClientException, which " +
"means the client encountered " +
"an internal error while trying to " +
"communicate with S3, " +
"such as not being able to access the network.");
System.out.println("Error Message: " + ace.getMessage());
}
return new ResponseEntity<>(HttpStatus.OK);

}

}

问题是我没有收到任何错误,但文件没有上传到 s3-bucket。我在这里错过了什么吗?提前致谢

最佳答案

当流直接上传到S3时,应在请求中指定内容长度。

ObjectMetadata objMetadata = new ObjectMetadata()
objMetadata.setContentLength(20L);

When uploading directly from an input stream, content length must be specified before data can be uploaded to Amazon S3. If not provided, the library will have to buffer the contents of the input stream in order to calculate it. Amazon S3 explicitly requires that the content length be sent in the request headers before any of the data is sent.

Refer this for content length calculation

替代方法:-

使用org.springframework.util.FileCopyUtils.copyToByteArray()将流转换为byte[]并将字节数组上传到S3。

关于java - 文件未上传到 s3 存储桶,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47343828/

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