Change filename when using express/multer

前端 未结 3 605
长发绾君心
长发绾君心 2021-02-10 11:04

I\'m having trouble uploading a pdf, when I upload it (I\'m using ng-file-upload) the file json that reachs express.js is:

{ fieldname: \'file\',
           


        
相关标签:
3条回答
  • 2021-02-10 11:40
    var storage = multer.diskStorage({
      destination: function (req, file, cb) {
        cb(null, './uploads/')
      },
      filename: function (req, file, cb) {
    
          cb(null,  file.originalname );
    
      }
    });
    var upload = multer({ storage: storage });
    

    Configure like this in your express

    0 讨论(0)
  • 2021-02-10 11:46

    In Angular you need to move new_file_name to be above file in data as follows:

        Upload
            .upload( {
                url: '/upload',
                data: {
                    new_file_name: vm.new_name, //this is the filename I want
                    file: vm.pdf
                }
            } )
    

    Basically browser needs to send that data before the file ... Better explanation can be found here: https://github.com/expressjs/multer/issues/134

    0 讨论(0)
  • 2021-02-10 11:58
    var express = require( 'express' ),
        router  = express.Router(),
        util    = require( 'util' ),
        multer  = require( 'multer' );
    
    var storage = multer.diskStorage(
        {
            destination: './uploads/',
            filename: function ( req, file, cb ) {
                //req.body is empty...
                //How could I get the new_file_name property sent from client here?
                cb( null, file.originalname+ '-' + Date.now()+".pdf");
            }
        }
    );
    
    var upload = multer( { storage: storage } );
    
    router.route( '/upload' )
        .post( upload.single( 'file' ), post );
    
    function post( request, response ) {
    
        response.json( { message: 'Files Uploaded!' } );
    
    }
    
    0 讨论(0)
提交回复
热议问题