javascript - 使用预签名 URL 上传后,AWS S3 上的文件在文件中有额外信息
问题描述
我正在尝试使用预签名的 url 将文件直接上传到 S3 存储桶。
下面是用node.js编写的服务器端代码,它成功创建了签名的url。
const s3 = new AWS.S3({
accessKeyId: config.accessKeyId,
secretAccessKey: config.secretAccessKey,
region: config.awsConfig.region
});
const signedUrlExpireSeconds = 60 * 60;
let mimeType = "video/mp4";
const filename =Date.now();
const Key = `${filename}.mp4`;
const params = {
Bucket: config.awsConfig.aws_upload_bucket,
Key: Key,
Expires: signedUrlExpireSeconds,
ACL: 'public-read',
ContentType: mimeType
};
s3.getSignedUrl('putObject', params, function (err, url) {
if (err) {
console.log('Error getting presigned url from AWS S3');
res.json({ success: false, message: 'Pre-Signed URL error', urls: fileurls });
}
else {
console.log('Presigned URL: ', url);
res.json({ success: true, message: 'AWS SDK S3 Pre-signed urls generated successfully.', url: url, Key:Key, ContentType: mimeType });
}
});
下面是在 React 端编写的代码。
const DropzoneArea = props => {
const [files, setFiles] = useState([]);
let awsFile = '';
const onUploadHandler = files => {
if (files.length === 0) {
console.log('Debug : [components DropzoneArea onUploadHandler] files => ', files);
return;
}
awsFile = files[0]
// calling the API to get presigned url.
getPreSignedURL(files[0].type,S3preSignedURLCallback)
};
const S3preSignedURLCallback = videoData => {
const xhr = new XMLHttpRequest();
xhr.open('PUT', videoData.url);
xhr.setRequestHeader('Content-Type', videoData.ContentType);
var res = new FormData();
res.append('file', awsFile);
xhr.send(res);
};
}
使用上面的代码文件成功上传到s3,但视频无法播放。因此,我将 S3 上的文件与我上传的实际文件进行了比较。我发现很少有额外的请求数据也写在 S3 文件中。
我在这里做的一个小错误,找不到错误。请帮忙。
解决方案
不要使用formData
,直接发送文件。
const S3preSignedURLCallback = videoData => {
const xhr = new XMLHttpRequest();
xhr.open('PUT', videoData.url);
xhr.setRequestHeader('Content-Type', videoData.ContentType);
// Send the binary data.
// Since a File is a Blob, you can send it directly.
xmlHttpRequest.send(awsFile);
};
您看到的不同之处在于,AWS 正在保存原始请求,而不对其进行解析,并且您可以看到正确的图像是一个多部分/表单数据请求。
推荐阅读
- javascript - 在Node js中登录身份验证时出错
- java - 每当我运行由 java.lang.nullpointerException 引起的应用程序时,我都会收到此错误:findViewbyId(R.id.btn_start)must not be null
- python - Tkinter 窗口浮动在 i3 中,但也适用于 MS-Windows
- javascript - 过滤不等于特定文本jqgrid的数据
- flutter - 颤振中的上下文问题“未定义的名称'上下文'”
- docker - 使用 docker 运行 jmeter
- cypress - 与赛普拉斯的元素查询不一致
- blockchain - 如何通过保持相同的 CID 将文件上传到 IPFS
- google-chrome - 加载资源失败:服务器响应状态为 401 ()
- javascript - 如何使用循环绘制多个正方形以仅在 java 脚本中更改位置?