ng2FileUpload库-添加多个formData

时间:2018-12-03 09:57:57

标签: javascript angular ng2-file-upload

我添加到了'uploader.onBeforeUploadItem'方法代码,如下所示:

item.formData['creator'] = {
    id: user.id,
    name: user.name,
    avatar: user.avatar
};
item.formData['content'] = 'value';

此外,我还从输入类型文件中添加了一个文件:

<form enctype="multipart/form-data">
    <div class="textfield" contenteditable [innerHTML]="content"></div>
    <div *ngIf="scope.imageLoaded" class="image-gallery">
        <div class="image-preview" [ngStyle]="{'background-image' : 'url(' + scope.addImgPath + ')'}"></div>
    </div>
    <button (click)="uploader.uploadAll()" class="btn right grey darken-4 send-message" type="submit">Send
        <i class="material-icons right">send</i>
    </button>
</form>

问题是,当我尝试在后端站点上引用此值时,我只能获得的属性是该文件。其他数据在那里不可见(req.body未定义):

router.post('/add', (req, res) => {
    upload(req, res, (err) => {

        let newPost = new Post({
            content: req.body.content,
            creator: req.body.creator,
            post_date: Date.now(),
            rate: 0,
            users_liked: [],
            image: 'http://localhost:3000/uploads/' + req.file.filename
        });

        Post.addPost(newPost);
    });
});

当我通过控制台的xhr选项卡检查请求时,我看到唯一的发送数据是文件。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

如下更新您的onBeforeUplaodItem回调-

onBeforeUploadItem(item: FileUploader | any) {
    item.formData.push({
        "creator": {
            id: user.id,
            name: user.name,
            avatar: user.avatar
        },
        "content": "value"
    });
}

您将使用上面的代码获得一个JSON。