Node.js and Multer - Handle the destination of the uploaded file in callback function (req,res)

前端 未结 3 1145
孤城傲影
孤城傲影 2021-02-04 19:05

I\'m new to Node.js and I ran into a simple problem lately.

I\'m using multer module to upload images. In my web app all the users have a unique id, and I wa

3条回答
  •  时光说笑
    2021-02-04 19:45

    You can accomplish this using multer to handle the dynamic creation of upload directory. The input parameter(for which you want to create a directory) should be called before sending a file name.

    var express = require('express');
    var app = express();
    var multer = require('multer');
    var fs = require('fs');
    var mkdirp = require('mkdirp');
    var bodyParser = require('body-parser');
    app.use(bodyParser.json({limit: '5mb'}));
    app.use( bodyParser.json() );       // to support JSON-encoded bodies
    app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
        extended: true,
        limit: '5mb'
    }));
    
    var storage =   multer.diskStorage({
        destination: function (req, file, callback) {
            var Id = req.body.id;
            upload_path = "./"+Id;
            mkdirp(upload_path, function (err) {
                if (err) console.error(err)
                else {
                    console.log('Directory created');
                    //setting destination.
                    callback(null, upload_path);
                }
            });
    
        },
        filename: function (req, file, callback) {
            callback(null, file.orginalname)
        }
    });
    //multer setting and getting paramaters.
    var upload = multer({ storage : storage }).single('upload_file');
    
    //creating request for upload file
    app.post('/uploadFile', function(req, res){
        res.set({ 'content-type': 'application/json; charset=utf-8' });
        res.header("Content-Type", "application/json; charset=utf-8");
        res.header("Access-Control-Allow-Origin", "*");
        res.charset = 'utf-8';
        //function upload_process(){
        upload(req, res, function(err){
            if(err){
                console.log('Error-->');
                console.log(err);
                res.json({"status": "Failure", "message":'There was a problem uploading your files.'+err});
                return;
            }
            else{
                console.log("fieldname"+req.files.length);
                if( req.files.length != 0){
                    res.json({"status" : "Success", "message":'Your files are uploaded.'});
                    console.log('File uploaded!');
                }
                else{
                    console.log("No file uploaded. Ensure file is uploaded.");
                    res.json({"status" : "Failure", "message" : 'No file uploaded. Ensure file is uploaded.'});
    
                }
            }
        });
    
    });
    
    });
    

    Hope this helps! Happy coding

提交回复
热议问题