XHR上传onprogress事件不适用于HTTPS连接

时间:2019-02-27 20:26:19

标签: javascript node.js angular https xmlhttprequest

我有一个用于通过Angular 7和Node.Js将文件上传到AWS S3的设置。上传正常。但是xhr.upload.onprogress事件存在问题。

仅当通过http托管服务器时才触发此事件。使用https连接时,不会一次触发该事件。

我在heroku和我的EC2实例上对其进行了测试,并得出结论,只有http有效。因此,我通过https托管在AWS上的生产应用程序也不起作用。

这是代码(如果需要更多详细信息,请写注释):

Angular Service(前端)

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);
        })
})

我真的很困惑为什么会这样。我找不到关于此问题的在线资源。

我真的很感谢大家的帮助!

谢谢

1 个答案:

答案 0 :(得分:0)

这是我用于Web项目的基本js代码:

        ...
        var xhr = new XMLHttpRequest();

        xhr.upload.addEventListener("progress", uploadProgress, false);

        xhr.addEventListener("load", uploadComplete, false);

        xhr.addEventListener("error", uploadFailed, false);

        xhr.addEventListener("abort", uploadCanceled, false);

        xhr.open("POST", "/controller");
        // fd : formData
        xhr.send(fd);

    }

    function uploadProgress(evt) {

        if (evt.lengthComputable) {

            var percentComplete = Math.round(evt.loaded * 100 / evt.total);
            ...
        }

        else {

            ...
        }

    }

正如您所看到的,我在'progress'上添加了一个事件侦听器,我没有像(=)一样覆盖其他回调函数(也许https使用另一个回调并像在回调无法正常运行):

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 });
    }
};

尝试一下,希望对您有所帮助