2013-04-17 3 views
0

node.js을 사용하여 파일을 업로드하고 있습니다. 그러나 임의의 이름 (예 : 132d439bb31ee13daaf6ce02e223738f)을 사용하여 /tmp 폴더에 파일을 업로드합니다. 노드가 주어진 이름의 주어진 디렉토리에 파일을 업로드하길 원합니다. 어떻게 만들 수 있습니까?node.js에 업로드 된 파일의 이름을 변경하십시오.

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 
} 

답변

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; 
     }); 

을하고 문제가

를 해결 여기에 내 코드입니다
관련 문제