【问题标题】:Changing file name using multer in node JS在节点 JS 中使用 multer 更改文件名
【发布时间】:2016-05-28 10:13:57
【问题描述】:

我正在尝试在客户端使用 ng-file-upload 更改图像名称,并在节点 JS 上使用 multer 作为解析器。

我的服务器代码:

var express = require("express");
var app = express();
var server = require("http").createServer(app);
var bodyParser = require('body-parser');
app.use(express.static(__dirname));
var jsonParser = bodyParser.json();
var multer = require('multer');

var storage = multer.diskStorage({ //multers disk storage settings
        destination: function (req, file, cb) {
            cb(null, './content/uploads/')
        },
        filename: function (req, file, cb) {
            var datetimestamp = Date.now();
            cb(null, file.fieldname + '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length -1]);
            //cb(null,"how are you" + '.' + file.originalname.split('.')[file.originalname.split('.').length -1]);
        }
 });

//multer settings
var upload = multer({storage: storage}).single('file');

/** API path that will upload the files */
app.post('/imageUpload',function(req, res) {
    upload(req,res,function(err){
        if(err){
             res.json({error_code:1,err_desc:err});
             return;
        }
         res.json({error_code:0,err_desc:null});
    })

});
app.get('/*',function(request,response){
    response.sendFile(__dirname + '/index.html');
});
server.listen(8080, function() {
    console.log("Express node js server listening on port %d...", this.address().port);
});

我的控制器代码:

uploadImagesApp.controller('HomeController',['$scope','uploadImageFactory','Upload','$window',function($scope,uploadImageFactory,Upload,$window){
    $scope.file;
    $scope.submitForm = function(form){ //function to call on form submit
        if (form.file.$valid && $scope.file) { //check if from is valid
            $scope.upload($scope.file); //call upload function
        }
    }

    $scope.upload = function (file) {
        Upload.upload({
            url: 'http://127.0.0.1:8080/imageUpload', //webAPI exposed to upload the file
            data:{file:file} //pass file as data, should be user ng-model
        }).then(function (resp) { //upload function returns a promise
            if(resp.data.error_code === 0){ //validate success
                $window.alert('Success ' + resp.config.data.file.name + 'uploaded. Response: ');
            } else {
                $window.alert('an error occured');
            }
        }, function (resp) { //catch error
            console.log('Error status: ' + resp.status);
            $window.alert('Error status: ' + resp.status);
        }, function (evt) { 
            console.log(evt);
            var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
            console.log('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);
            $scope.progress = 'progress: ' + progressPercentage + '% '; // capture upload progress
        });
    };
}]);

和我的html查看代码:

<form ng-submit="submitForm(uploadForm)" enctype="multipart/form-data" name="uploadForm">
    <input type="text" name="fileName" id="image-name"/>
    <input type="file" ngf-select ng-model="file" name="file" ngf-pattern="'image/*' "accept="image/*" required/>
    Image thumbnail: <img style="width:100px;" ngf-thumbnail="file || '/thumb.jpg'"/>
    <button type="submit">Upload Image</button>
    <p>{{progress}}</p>
</form>

我想在表单中获取文件名并将图像和文件名发送到节点 js。 但是当我尝试使用 req.body.fileName 时,我得到了未定义。 这样做的正确方法是什么,这样我就可以将文件名与图像文件一起传递?

谢谢。

【问题讨论】:

  • 在代码的哪一点你转向req.body.fileName
  • 好吧,我在调用上传和文件名函数之后以及在调用上传之前尝试过,但在所有这些地方 req.body.filename 都是未定义的
  • 您可以使用Upload.rename()在客户端使用ng-file-upload重命名文件。

标签: javascript angularjs node.js multer ng-file-upload


【解决方案1】:

我认为您只是在提交表单时没有通过必填字段。尝试改变:

html 视图

<input type="text" name="fileName" id="image-name" ng-model="filename" required/>

控制器代码

data:{file:file, filename: $scope.filename}

服务器端

app.post('/imageUpload',function(req, res) {
    upload(req,res,function(err){
        console.log(req.body.filename);
        if(err){
             res.json({error_code:1,err_desc:err});
             return;
        }
         res.json({error_code:0,err_desc:null});
    })    
});

【讨论】:

    【解决方案2】:

    我解决了我的问题。

    Upload.upload({
                url: 'http://127.0.0.1:8080/imageUpload',//webAPI exposed to upload the file
                fields: {
                    newFileName: $scope.fileName
                },
                file: file
                //data:{file:file} //pass file as data, should be user ng-model
            })
    

    我添加的字段让我可以访问 req.body.newFileName。

    谢谢大家的帮助!

    【讨论】:

      猜你喜欢
      • 2016-06-25
      • 2017-08-30
      • 1970-01-01
      • 2016-03-06
      • 1970-01-01
      • 1970-01-01
      • 2020-07-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多