我正在尝试使用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。我在这里错过了什么吗?提前致谢
答案 0 :(得分:1)
当流直接上传到S3时,应在请求中指定内容长度。
ObjectMetadata objMetadata = new ObjectMetadata()
objMetadata.setContentLength(20L);
直接从输入流上传时,内容长度必须为 在将数据上传到Amazon S3之前指定。如果没有提供, 库必须缓冲输入流的内容 为了计算它。 Amazon S3明确要求提供内容 在发送任何数据之前,请在请求标头中发送长度。
Refer this for content length calculation
替代方法: -
使用org.springframework.util.FileCopyUtils.copyToByteArray()
将流转换为byte[]
并将字节数组上传到S3。