How to upload file using multer or body-parser

后端 未结 4 1896
感动是毒
感动是毒 2021-01-17 12:34

I am a NodeJS beginner, following along a book \"Web Development with MongoDB and NodeJS\". I am stuck at its chapter 6 with \'multer\'. When I use multer for file uploads t

相关标签:
4条回答
  • 2021-01-17 12:47

    I corrected the code of the book "Web Development with MongoDB and NodeJS" as follows:

    app.use(multer({dest:path.join(__dirname,'../public/upload/temp')}).any());
    .
    .
    .
    .
    const tempPath = req.files[0].path,  // Temporary location of uploaded file
    ext = path.extname(req.files[0].originalname).toLowerCase(), // Get file extension of the uploaded file
    targetPath = path.resolve(`./public/upload/${imgUrl}${ ext}`); // The final path for the image file
    
    
    

    The other parts of code remained intact. It worked and I could upload image files. Best wishes, Mehrdad Sheikhan

    0 讨论(0)
  • 2021-01-17 12:57

    multer() returns a middleware generator that uses the settings you specified, so you cannot pass its return value directly to app.use(). You can see all of the types of middleware it can generate in the documentation, but typically the generated middleware are added at the route level instead of globally like the other body parsers. This is because you will typically pass in the name of the file field(s) that you will be expecting.

    For example, this will accept a single file (along with any non-file fields) whose form field name is foo:

    var upload = multer({
      dest: path.join(__dirname, '../public/upload/temp')
    });
    
    // ...
    
    app.post('/upload', upload.single('foo'), function(req, res) {
      if (req.file) {
        console.dir(req.file);
        return res.end('Thank you for the file');
      }
      res.end('Missing file');
    });
    

    Also, body-parser does not currently export a multipart/form-data-capable middleware, so you cannot use that module for handling uploaded files (well, short of passing a base64-encoded string in an application/x-www-form-urlencoded form or something, but that's much less efficient).

    0 讨论(0)
  • 2021-01-17 12:57

    Here is the basic code for file upload in MEAN please check

    HTML

    <form id="frmDoc" name="frmDocument" ng-submit="upload()" class="form-horizontal form-bordered" enctype="multipart/form-data" >
            <fieldset>
                <div class="form-group">
                    <label class="col-md-4 control-label" for="val_email">Document<span class="text-danger">*</span></label>
                    <div class="col-md-4">
                        <div class="input-group">
                        <input type="file" name="file" id='file' required="required" />
                        </div>
                    </div>
                </div>
            </fieldset>
            <div class="form-group form-actions">
                <div class="col-md-8 col-md-offset-4">
                    <button type="submit" class="btn btn-sm btn-primary"><i class="fa fa-upload"></i> submit</button>
                </div>
            </div>
        </form>
    

    CLIENT SIDE CODE

    app.controller ('myctrl',function($scope,$http){
    
      $scope.upload = function () {
                var file = angular.element(document.querySelector('#file')).prop("files")[0];
                    $scope.files = [];
                    $scope.files.push(file);
                    $http({
                        method: 'POST',
                        url: '/users/upload',
                        headers: { 'Content-Type': undefined },
                        transformRequest: function (data) {
                            var formData = new FormData();
                            formData.append('model', angular.toJson(data.model));
                            formData.append('file', data.files[0]);
                            return formData;
                        },
                        data: { model: { title: 'hello'}, files: $scope.files }
    
                    }).success(function (res) {
                        console.log(res)
                    });
            }
    
    
    });
    

    SERVER SIDE CODE

    var multer  = require('multer');
    var mkdirp = require('mkdirp');
    
    var storage = multer.diskStorage({
      destination: function (req, file, cb) {
        //var code = JSON.parse(req.body.model).empCode;
        var dest = 'public/uploads/';
        mkdirp(dest, function (err) {
            if (err) cb(err, dest);
            else cb(null, dest);
        });
      },
      filename: function (req, file, cb) {
        cb(null, Date.now()+'-'+file.originalname);
      }
    });
    
    var upload = multer({ storage: storage });
    
    router.post('/upload', upload.any(), function(req , res){
        console.log(req.body);
        res.send(req.files);
    });
    
    0 讨论(0)
  • 2021-01-17 12:57

    Code for upload file using Multer and save it to local folder

    api- call fileUpload function
    fileUpload(req)
        .then(uploadRes => {
            console.log('uploadRes', uploadRes)
        })
        .catch(err => {
            console.log('err', err)
        })
    
    
    Create file upload service
    const multer = require('multer') // import library
    const moment = require('moment')
    const q = require('q')
    const _ = require('underscore')
    const fs = require('fs')
    let dir = './public'
    
    /** Store file on local folder */
    let storage = multer.diskStorage({
        destination: function (req, file, cb) {
            cb(null, dir)
        },
        filename: function (req, file, cb) {
            let date = moment(moment.now()).format('YYYYMMDDHHMMSS')
            cb(null, date + '_' + file.originalname.replace(/-/g, '_').replace(/ /g, '_'))
        }
    })
    
    /** Upload files */
    let upload = multer({ storage: storage }).array('files')
    
    /** Exports fileUpload function */
    module.exports = {
        fileUpload: function (req) {
            let deferred = q.defer()
    
            /** Create dir if not exist */
            if (!fs.existsSync(dir)) {
                fs.mkdirSync(dir)
                console.log(`\n\n ${dir} dose not exist, hence created \n\n`)
            }
    
            upload(req, {}, function (err) {
                if (req && (_.isEmpty(req.files))) {
                    deferred.resolve({ status: 200, message: 'File not attached', data: [] })
                } else {
                    if (err) {
                        deferred.reject({ status: 400, message: 'error', data: err })
                    } else {
                        deferred.resolve({
                            status: 200,
                            message: 'File attached',
                            filename: _.pluck(req.files,
                                'filename'),
                            data: req.files
                        })
                    }
                }
            })
            return deferred.promise
        }
    }
    
    0 讨论(0)
提交回复
热议问题