【问题标题】:Change the name of uploaded file in node.js在 node.js 中更改上传文件的名称
【发布时间】:2013-04-17 08:49:32
【问题描述】:

我正在使用node.js 上传文件。但它会以随机的类似名称(例如:132d439bb31ee13daaf6ce02e223738f)上传/tmp 文件夹中的文件。我希望节点将文件上传到具有给定名称的给定目录中。我怎样才能做到?这是我的代码:

var http = require("http"),
    url = require("url"),
    sys = require("sys"),
    events = require("events"),
    fs = require("fs"),
    formidable = require('formidable'),
    util = require('util');

var server = http.createServer(function(req, res) {
    switch (url.parse(req.url).pathname) {
        case '/':
            display_form(req, res);
            break;
        case '/upload':
            upload_file(req,res);
            break;
        default:
            show_404(req, res);
            break;
    }
});

server.listen(8124);

function display_form(req, res) {
    //displays an html form with an upload and a submit button
}

function upload_file(req, res) {
    if (req.url == '/upload' && req.method.toLowerCase() == 'post') {

      // Instantiate a new formidable form for processing.

      var form = new formidable.IncomingForm();

      // form.parse analyzes the incoming stream data, picking apart the different fields and files for you.

      form.parse(req, function(err, fields, files) {
        if (err) {

          // Check for and handle any errors here.

          console.error(err.message);
          return;
        }
            form.on('fileBegin', function(name, files) {
                files.name="./guake.up";
            });
        res.writeHead(200, {'content-type': 'text/plain'});
        res.write('received upload:\n\n');

            console.log(files.name);

        // This last line responds to the form submission with a list of the parsed data and files.

        res.end(util.inspect({fields: fields, files: files}));
      });
      return;
    }
}

function show_404(req, res) {
    //shows a 404 page
}

【问题讨论】:

    标签: node.js file-upload formidable


    【解决方案1】:

    我找到了答案,我只需要在我的form.parse方法之前添加以下代码:

    form.on('error', function(err) {
                 throw err;
                 })
    
           /* this is where the renaming happens */
         .on ('fileBegin', function(name, file){
                 //rename the incoming file to the file's name
                 file.path = form.uploadDir + file.name;
          });
    

    问题解决了

    【讨论】:

      猜你喜欢
      • 2013-02-14
      • 1970-01-01
      • 1970-01-01
      • 2018-02-14
      • 1970-01-01
      • 2020-03-31
      • 2019-09-12
      • 2018-06-28
      • 2020-06-01
      相关资源
      最近更新 更多