本文介绍了Angular 6和Node Js AWS S3文件上传进度栏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我通过Angular 6(前端)和NodeJ(后端)将文件上传到asw-s3存储桶时,我试图创建一个进度条.如何获取进度(或已上传的字节)并在Angular 6前端中实时接收它们?

I'm trying to create a progress bar when uploading files via Angular 6 (frontend) and NodeJs (backend) to an asw-s3 bucket.How to fetch the progress (or the already uploaded bytes) and receive them in the Angular 6 frontend in realtime?

推荐答案

不确定angular是否有针对此的特定方法,但这是我在一些基于angular的网站中使用的有效示例:

Not sure if angular has a specific method for this, but here is a working example I used in some of my angular based websites :

sendFile(file) {
    let formData: FormData = new FormData();
    formData.append('my_file', file);

    let xhr = new XMLHttpRequest();
    xhr.upload.onprogress = function (progEvent: ProgressEvent) {
        if (progEvent.lengthComputable) {
            var uploadedSoFar = (progEvent.loaded / progEvent.total) * 100;
            console.log("Uploaded: " + uploadedSoFar + "% ")
            if (progEvent.loaded == progEvent.total){
                // uploaded up to 100%
            }
        }

    };
    xhr.open("POST", `/your_site`, true);
    xhr.send(formData);
}

对正在发生的事情的一些解释:

Some explanation of what is going on :

FormData

https://developer.mozilla.org/zh-CN/docs/Web/API/FormData

XMLHttpRequest

https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest

节点端我正在更新这篇文章,以添加一个节点代码示例(在评论之后).我在node.js中的表现不佳,因此以下代码不是一个很好的示例.

Node SideI'm updating this post to add a node code sample (after the comments). I am not as good in node.js, so my following code is not a good example.

const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  // Remove this, I use it for this example to be easy to reproduce
  res.setHeader('X-Frame-Options', 'ALLOWALL');
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'POST, GET');
  res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  if (req.method == 'POST') {
        console.log("Receiving file");
        var body = '';
        req.on('data', function (data) {
            body += data;
            console.log("receiving data : " + body);
        });
        req.on('end', function () {
            console.log("received all the data: " + body);
        });
        res.writeHead(200, {'Content-Type': 'text/html'});
        res.end('Reception completed');
    }

});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

如果您在node.js中接收到数据,则表明您的前台工作正常.

If you receive data in your node.js, this would mean that your front is working correctly.

这篇关于Angular 6和Node Js AWS S3文件上传进度栏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 03:10