【问题标题】:Send formdata with file in angular and sails.js发送带有角度和sails.js文件的formdata
【发布时间】:2018-11-14 13:08:46
【问题描述】:

我按照this 教程执行文件上传,并尝试使用它发送表单数据 下面是filechange事件的代码

    onFileChange(event) {
        let fileList: FileList = event.target.files;
        if (fileList.length > 0) {
            console.log("gettign file ...")
            let file: File = fileList[0];
            this.formData.append('photoupload', file, file.name);
        }
    }

当点击下面的提交按钮时,代码被执行

    let body = JSON.stringify(this.personal);
    this.formData.append("personal", body);
    const headers = new HttpHeaders({
        'Authorization' : 'my-auth-token'
    });

    this.http.post('/api/fmng/create', this.formData, {
        headers: headers
    }).subscribe(data => {
        console.log(data);
    });

在服务器端,我只能使用 req.file() 获取文件,但是当我执行 req.allParams() 时,其中没有数据。还尝试 console.log 表单数据在 Angular 应用程序中给出空结果。

编辑 -->

如果我只用正文发出另一个帖子请求,那么我会得到数据。因此,这可能不是附加表单数据的正确方法。

    this.http.post('/api/fmng/create', body, {
        headers: headers
    }).subscribe(data => {
        console.log(data);
    });

【问题讨论】:

    标签: angular sails.js


    【解决方案1】:
    onFileChange(event) {
            let fileList: FileList = event.target.files;
            if (fileList.length > 0) {
                console.log("gettign file ...")
                let file: File = fileList[0];
                const fileBlob= new Blob([file], { type: "<content-type>" });
                this.formData.append('photoupload', fileBlob);
            }
        }
    

    你需要在这里发送一个 blob。

    【讨论】:

    • 接收文件没有问题。我无法获取其他参数。
    【解决方案2】:

    在将文件附加到表单数据之前,我必须附加文本参数

        let body = JSON.stringify(this.personal);
        this.formData.append("personal", body);
        this.formData.append('photoupload', this.file, this.file.name);
        const headers = new HttpHeaders({
            'Authorization' : 'my-auth-token'
        });
    
        this.http.post('/api/fmng/create', this.formData, {
            headers: headers
        }).subscribe(data => {
            console.log(data);
        });
    

    这解决了问题。

    【讨论】:

      猜你喜欢
      • 2016-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-27
      • 2021-08-29
      • 1970-01-01
      • 2021-12-08
      • 1970-01-01
      相关资源
      最近更新 更多