淘先锋技术网

首页 1 2 3 4 5 6 7

跟着教程一步一步来的,链接:http://www.nodebeginner.org/index-zh-cn.html   但是文件上传那部分总是报错。

代码如下:

function upload(response, request) {
  console.log("Request handler 'upload' was called.");

  var form = new formidable.IncomingForm();
  console.log("about to parse");
  form.parse(request, function(error, fields, files) {
    console.log("parsing done");
    fs.renameSync(files.upload.path, "/tmp/test.png");
    response.writeHead(200, {"Content-Type": "text/html"});
    response.write("received image:<br/>");
    response.write("<img src='/show' />");
    response.end();
  });
}

报错:

估计又是权限的问题吧,把上述代码改为如下即可正确运行。

function upload(response, request) {
  console.log("Request handler 'upload' was called.");

  var form = new formidable.IncomingForm();
  console.log("about to parse");
  form.uploadDir = "./tmp"; // add this one
  form.parse(request, function(error, fields, files) {
    console.log("parsing done");
    console.log(files.upload.path);
    fs.renameSync(files.upload.path, "./tmp/1.jpg"); //also,change to ./tmp/1.jpg
    response.writeHead(200, {"Content-Type": "text/html"});
    response.write("received image:<br/>");
    response.write("<img src='/show' />");
    response.end();
  });
}