如何在angular 2 中使用ng2 文件上传提交post 数据?

How to submit post data with ng2 file upload in angular 2?

我在 angular 中使用 ng2-file-upload 2. 有什么方法可以通过文件上传操作提交我的表单数据吗?

我在使用 ng2-file-upload 时遇到了同样的问题。他们有一个名为 onBeforeUploadItem 的钩子。以下无效:

ngOnInit() {
 this.uploader.onBeforeUploadItem = (fileItem: any) => {
  fileItem.formData.push( { someField: this.someValue } );
  fileItem.formData.push( { someField2: this.someValue2 } );
 };
}

当我注销 fileItem.formData 的内容时,所有值都在那里。但是,这些表单元素似乎永远不会返回到服务器。我正在使用 Chrome,当我观察 HTTP post 时,我看到了以下内容:

请求Headers

POST /api/upload/csv HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Content-Length: 228
Origin: http://localhost:4200
x-access-token: eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJyb290IiwiYWRkciI6IjA6MDowOjA6MDowOjA6MSIsInNjaGVtZSI6Imh0dHAiLCJwb3J0IjoiODA4MCIsImlhdCI6MTQ2OTUwMzM1NX0.jICVQdZD-6m705sZsaQJ5-51LztdIx9pAAKgVYgL3HRMMgrJh6ldFbYvUVtA_UQkSrvCrNJeWeo4C7QYe2W4Cw
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryCSUTihSBrgmwjxg1
Accept: */*
Referer: http://localhost:4200/main
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8
Cookie: _ga=GA1.1.941072201.1467616449; token=eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJyb290IiwiYWRkciI6IjA6MDowOjA6MDowOjA6MSIsInNjaGVtZSI6Imh0dHAiLCJwb3J0IjoiODA4MCIsImlhdCI6MTQ2OTUwMzM1NX0.jICVQdZD-6m705sZsaQJ5-51LztdIx9pAAKgVYgL3HRMMgrJh6ldFbYvUVtA_UQkSrvCrNJeWeo4C7QYe2W4Cw

请求负载

------WebKitFormBoundaryCSUTihSBrgmwjxg1
Content-Disposition: form-data; name="file"; filename="data.csv"
Content-Type: text/csv


------WebKitFormBoundaryCSUTihSBrgmwjxg1--

实际解决方案

事实证明我很接近。解决方案是覆盖 onBuildItemForm.

ngOnInit() {
 this.uploader.onBuildItemForm = (fileItem: any, form: any) => {
  form.append('someField', this.someValue); //note comma separating key and value
  form.append('someField2', this.someValue2);
 };
}

实例 form 的类型为 FormData。通过查看我的 HTTP post,我可以看到我的表单字段值被发送到服务器,我的服务器现在确实看到了这些值。

this.uploader.onBeforeUploadItem = (item: FileItem) => {
  item.withCredentials = false;
  this.uploader.authToken = 'Bearer ' + this.boxTokenResponse.userToken;
  this.uploader.options.additionalParameter = {
    name: item.file.name,
    parent_id: this.parentFolderId
  };
};

这就是 file-uploader.class.js 平移表单数据的方式。

if (!this.options.disableMultipart) {
        sendable = new FormData();
        this._onBuildItemForm(item, sendable);
        sendable.append(item.alias, item._file, item.file.name);
        if (this.options.additionalParameter !== undefined) {
            Object.keys(this.options.additionalParameter).forEach(function (key) {
                sendable.append(key, _this.options.additionalParameter[key]);
            });
        }
    }

至于访问服务器中的数据,可以使用Multer:

    const multer = require('multer');
    let DIR = './uploads/';

    let upload = multer({dest: DIR}).single('givenitemAlias');
        router.post('/upload', function (req, res, next) {
            console.log(req.body);//empty object
            upload(req, res, function (err) {
                if (err) {
                    // An error occurred when uploading
                    return res.status(422).send("an Error occured")
                }
                // No error occured.
                console.log(req.body);//modified req.body with out key value pairs
                console.log(req.file);//metadata of the file
                return res.send("Upload Completed for "+temppathOfUploadedFile);
            });            
        });