Angular 6和Node Js AWS S3文件上传进度栏

时间:2018-07-04 15:00:17

标签: node.js angular amazon-s3

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

2 个答案:

答案 0 :(得分:2)

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

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

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

FormData

  

FormData接口提供了一种轻松构造一组   表示表单字段及其值的键/值对,可以   然后可以使用XMLHttpRequest.send()方法轻松发送。它用   如果将编码类型设置为,则表单将使用相同的格式   “ multipart / form-data”

https://developer.mozilla.org/en-US/docs/Web/API/FormData

XMLHttpRequest

  

使用XMLHttpRequest(XHR)对象与服务器进行交互。您可以   从URL检索数据,而无需刷新整个页面。   这使得网页可以更新页面的一部分而无需   破坏用户的行为。

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest

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

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中接收到数据,则表明您的前台工作正常。

答案 1 :(得分:2)

您可以仅使用常规HttpClient上传文件并使用标志reportProgress: true

完整示例:

constructor(private _http: HttpClient,
            private _logger: Logger) {}

this._http
    .post(FILE_UPLOAD_URL, formData, {
          reportProgress: true,
          observe: 'events'
        })
        .subscribe((event: HttpEvent<any>) => {
            switch (event.type) {
                case HttpEventType.Sent:
                    this._logger.debug('Upload started');
                    break;
                case HttpEventType.DownloadProgress:
                    // Live stats are also possible for downloads
                case HttpEventType.UploadProgress:
                    if (event.total) {
                         const progress = Math.round(event.loaded / event.total * 100);
                         const timeElapsed = Date.now() - startTime;
                         const uploadSpeed = event.loaded / (timeElapsed / 1000);
                         const uploadTimeRemaining = Math.ceil(
                                            (event.total - event.loaded) / uploadSpeed
                                        );
                         const uploadTimeElapsed = Math.ceil(timeElapsed / 1000);
                         const uploadSpeed = uploadSpeed / 1024 / 1024;
                         this._logger.debug('Upload stats:', progress, timeElapsed, uploadSpeed, uploadTimeRemaining,  uploadTimeElapsed, uploadSpeed);

                         break;
                     case HttpEventType.Response:
                          this.progressForFile = 100;
                          this._logger.debug('Done! ResponseBody:', event.body);

                 });

如果有希望,这会有所帮助! :-)