简体   繁体   English

如何使用multer上传文件/在表格数据中过帐?

[英]How to use multer to upload file/to do Post in form-data?

This is the productsModel.js file 这是productsModel.js文件

'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var productsSchema = new Schema({
      name: {
        type: String,
        required: true
      },
      cost: {
          type: Number
      },
      product_imagePaths: [{
          type: String
      }]
    });

module.exports = mongoose.model('Products', productsSchema);

And this is the code of my productsController.js 这是我的productsController.js的代码

var mongoose = require('mongoose'),
Products = mongoose.model('Products');


exports.uploadProducts = function(req,res) {
    var new_product = new Products(req.body)
    new_product.save(function(err,product){
        if(err) {
            res.send(err);
         }
         res.status = 200;
         res.json({
            "status":"success"
         });
     }); 
};

productsRoutes.js productsRou​​tes.js

'use strict';
module.exports = function (app) {
  var productsController = require('../controllers/productsController');

  app.route('/products')
    .get(productsController.fetchAllProducts)
    .post(productsController.uploadProducts);
};

In my server.js 在我的server.js中

// mongoose instance connection url connection
mongoose.Promise = global.Promise;
var db = mongoose.connect('mongodb://localhost/abcd', {
    useMongoClient: true
}); 


 // body parser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true }));

// route
var userRoutes = require('./api/routes/userRoutes');
var aboutUsRoutes = require('./api/routes/aboutusRoutes');
var productsRoutes = require('./api/routes/productsRoutes');
userRoutes(app);
aboutUsRoutes(app);
productsRoutes(app);

Now this works when I'm using x-www-form-urlencoded . 现在这在我使用x-www-form-urlencoded But since I want to upload a file via the Post method(uploadProducts in productsController.js), it can be done only via form-data . 但是由于我想通过Post方法(productsController.js中的uploadProducts)上传文件,因此只能通过form-data However, it doesn't work with form-data . 但是,它不适用于form-data I read that multer can be used for form-data upload, but I'm clueless as to how to use it in the following methodology. 我读到multer可用于上载form-data ,但对于如何在以下方法中使用它一无所知。

You want to use multer as middleware before calling your uploadProducts function. 您希望在调用uploadProducts函数之前将multer用作中间件。

Here is an example setup for productRoutes.js 这是productRoutes.js的示例设置

'use strict';
 const multer = require('multer')
 const storage = multer.memoryStorage()
 const upload = multer({
      storage: storage,
      limits: {
        fileSize: 5000000,
        files: 1
      }
    })
module.exports = function (app) {
  var productsController = require('../controllers/productsController');

  app.route('/products')
    .get(productsController.fetchAllProducts)
    .post(upload.single('img'), productsController.uploadProducts);
};

This will create a Buffer of your image which you can access in your productsController.js with req.file.buffer . 这将创建图像的Buffer ,您可以使用req.file.bufferproductsController.js进行req.file.buffer

Note that upload.single is a built in function for multer . 需要注意的是upload.single是一个内置的功能multer Read more about other functions here . 在此处阅读有关其他功能的更多信息。 Also img needs to match the name of your input field, ie <input type="file" name="img"> 同样, img需要匹配您输入字段的名称,即<input type="file" name="img">

This is just one of many one ways to do it. 这只是多种方法之一。 Hope it helps! 希望能帮助到你!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 Fetch 和 Multer 上传文件并在同一请求中发布表单数据? - How do I upload a file using Fetch and Multer and post form data in the same request? 如何将多部分/表单数据从 Angular 发布到 Nodejs Multer? - How to post multipart/form-data from Angular to Nodejs Multer? Multer 没有识别 multipart/form-data 请求文件 - Multer is not identifying the multipart/form-data request file 如何在不使用multipart / form-data的情况下使用reactjs上传文件? - How do I upload a file with reactjs without using multipart/form-data? 如何使用node.js(express.js)将带有上传文件的多部分/表单数据表单重新发送到不同的服务器? - how to resend post multipart/form-data form with upload file to different server with node.js (express.js)? Nodejs:Unirest:如何使用 multipart/form-data 上传文件 - Nodejs: Unirest: How to upload file with multipart/form-data 使用Multer上传文件,而无需使用表单标签上的操作,方法,encrypt =“ multipart / form-data”属性 - Upload files with Multer without using action, method, encrypt=“multipart/form-data” attributes on form tag 带有Post Method和enctype的表单Multipart / form-data不在Nodejs Express multer模块上提交 - Form with Post Method and enctype Multipart/form-data is not being submitted on Nodejs Express multer module Imgur上传api错误总是返回400与multer和form-data nodejs - Imgur upload api error always returning 400 with multer and form-data nodejs 要上传文件,在 post body 与 multipart/form-data 中发送 base64 的优缺点是什么 - To upload a file what are the pros and cons of sending base64 in post body vs multipart/form-data
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM