我有一个通过 Angular 7 和 Node.Js 将文件上传到 AWS S3 的设置。上传工作正常。但有一个问题xhr.upload.onprogress
event.
仅当通过托管服务器时才会触发此事件http
。当使用https
连接时,该事件不会触发一次。
我在 Heroku 和我的 EC2 实例上进行了测试,得出的结论是:http
作品。因此,我的生产应用程序通过以下方式托管在 AWS 上https
,也不起作用。
这是代码(如果需要更多详细信息,请写评论):
角度服务(前端)
const xhr = new XMLHttpRequest();
let progress = 0;
xhr.upload.onprogress = (event: ProgressEvent) => {
console.log('xhr on upload', event);
if (event.lengthComputable) {
progress = 100 * (event.loaded / event.total);
console.log('file upload progress', { progress, file });
}
};
xhr.responseType = 'json';
xhr.open('POST', `${API_URL}/${this.API_PATH}/upload`, true);
xhr.setRequestHeader('authorization', this.authService.getAuthToken());
xhr.send(payload);
xhr.onload = () => {
observer.next(xhr.response);
observer.complete();
alive = false;
};
Node.Js
module.exports = async (req, res) => {
try {
const busboy = new Busboy({ headers: req.headers })
busboy.on('finish', async () => {
const fileData = req.files.file
const fileId = req.body.fileId
await uploadToAws(fileData)
// ...
})
req.pipe(busboy)
} catch (err) { /* ... */ }
}
const uploadToAws = async (fileData, file) => {
return new Promise((resolve, reject) => {
const params = {
Body: fileData.data,
Bucket: awsConfig.buckets.drakery,
ContentType: fileData.mimetype,
Key: `mykey`,
StorageClass: 'ONEZONE_IA',
}
awsConfig.s3
.upload(params, (err, data) => err ? reject(err) : resolve(data.Location))
.on('httpUploadProgress', function (evt) {
console.log('httpUploadProgress', evt);
})
})
我真的很困惑为什么会发生这种情况。我在网上找不到任何关于这个问题的资源。
我真的很感谢每一个帮助!
Thanks