登录
注册
node.js 学习社区
关于Node.js入门书中例子的一个扩展问题

卷卷儿

2014-12-18 14:45

在Node.js入门书中最后部分。我们上传了照片,然后现在照片,假如我们上传了照片,照片的名字不是test.png,而是照片本身的名字。那在show函数中怎么去显示这张照片呢

就是怎么从upload中传递照片名字给show函数

下面是我的代码

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

  // using formidable
  var form = new formidable.IncomingForm();

  // set form encoding as utf-8
  form.encoding = "utf-8";

  var path = process.cwd();
  if("win32" == process.platform){
    path += "\\tmp\\";
  } else {
    path += "/tmp/";
  }

  console.log("Current Work Directory -> " + process.cwd());
  console.log("Current Operator System -> " + process.platform);
  console.log("Current File Path -> " + path);

  // set default upload folder
  form.uploadDir = path;

  console.log("about to parse ... ");
  form.parse(request, function(error, fields, files){
    console.log("parsing done ... ");

    var filename = files.upload.name;
    console.log("filename = " + filename);

    try{
      fs.renameSync(files.upload.path, path + filename);
    }catch(e){
      console.log("Rename Exception --> " + e);
    }

    response.writeHead(200, {"Content-Type": "text/html"});
    response.write("received image:<br/>");
    response.write("<img src='/show' />"); // send show request
    response.end();
  })
}

function show(response){
  console.log("Request handler 'show' was called ... ");

  fs.readFile("./tmp/test.png", "binary", function(error, file){
    if(error){
      response.writeHead(500, {"Content-Type": "text/plain"});
      response.write(error + "\n");
      response.end();
    }else{
      response.writeHead(200, {"Content-Type": "Image/png"});
      response.write(file, "binary");
      response.end();
    }
  });
}

不好意思,完全没有web编程的概念,请教了。。。。

原文引自:http://cnodejs.org/topic/4f716ac28a04d82a3d2074d3

回复 · 0

发表回复

你可以在回复中 @ 其他人