【问题标题】:How to save form data that include image using nodejs posted using angular 2如何使用使用 Angular 2 发布的 nodejs 保存包含图像的表单数据
【发布时间】:2018-04-27 09:41:04
【问题描述】:

我正在使用平均堆栈创建一个应用程序,其中我在客户端使用 angular 2。我创建了一个包含一些输入字段和图像的表单。现在,为了提交表单,我使用 formdata 将数据发送到节点服务器。现在我无法在节点服务器上显示、访问和保存数据。请有人帮助我,因为我是新手。

数据数组:

const newProduct = {
    category: this.pcategory,
    name: this.name,
    description: this.description,
    price: this.price,
    quantity: this.quantity,
    image: this.fileName
} 

这里是发送数据的代码: imagedata 包含文件的数据

addProduct(newProduct, imagedata:File) {
    let formData: FormData = new FormData();
    formData.append('body', JSON.stringify(newProduct));
    formData.append('file', image, newProduct.imagedata);
    let headers = new Headers();
    headers.append("enctype", "multipart/form-data"); 
    headers.append("Accept", "application/json");
    let options = new RequestOptions({ headers: headers });
    return this.http.post('http://localhost:3000/product/add' ,formData, options).map((response: Response) => response.json());
}

这里是接收和保存数据的代码:

function (req, res) {

        var storage = multer.diskStorage({//multers disk storage settings

            destination: function (req, file, callback) {

                callback(null, './uploads');

            }

        });
        var upload = multer({//multer settings

            storage: storage

        }).any();

        var model = new Model(req.body);
        model.save(function (err) {
            if (err) {
                return res.status(400).send({
                    message: errorHandler.getErrorMessage(err)
                });
            } else {
                res.status(201).json(model);
            }
        });
        upload(req, res, function (err) {
            if (err) {
                // An error occurred when uploading
                console.log(err);
                return res.status(422).send("an Error occured")
            }
        });
    }

【问题讨论】:

  • 可能与以下内容重复:stackoverflow.com/questions/42508558/…
  • 该问题仅包括图像上传,但我也在提交数据。我已经单独完成了图片上传和表单提交,但无法一起完成

标签: node.js mongodb express angular2-forms


【解决方案1】:

在 Angular 2 中,您无法使用此方法上传图像,请考虑使用此 Angular 2 模块ng2-file-uploader。你可以在这里Angular File Uploads with an Express Backend 查看演示应用程序。

【讨论】:

  • 我不想使用任何其他模块。是否有可能使用平均堆栈和角度2的基本概念来做到这一点??
  • 是使用 JS 表单数据对象发送图像。这是链接如何使用它developer.mozilla.org/en-US/docs/Web/API/FormData/append
  • 查看我使用的代码,但仍然没有结果。它显示空白 req.body
【解决方案2】:

一种解决方案可能是将您的图像转换为 base64 字符串并将该字符串传递到您的模型中。然后让 base64 字符串转换回服务器中的图像。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-05
    • 1970-01-01
    • 2019-07-20
    • 2020-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多