节点js中的图像上传

时间:2012-09-21 05:35:53

标签: node.js file-upload

我是节点js的新手,现在我想做图像上传。所以我下载了快速框架来处理上传。请帮我解决如何在服务器端处理上传。

我创建了这样的表单如何在后端节点js

中处理它
  <form method="post" enctype="multipart/form-data" action="/file-upload">
<input type="text" name="username">
<input type="password" name="password">
<input type="file" name="thumbnail">
<input type="submit">

1 个答案:

答案 0 :(得分:2)

使用此方法上传

app.post('/upload', function(req, res) {

    // get the temporary location of the file
    var tmp_path = req.files.thumbnail.path;
    // set where the file should actually exists - in this case it is in the "images" directory
   target_path = '/tmp/' + req.files.thumbnail.name;
    // move the file from the temporary location to the intended location
    fs.rename(tmp_path, target_path, function(err) {
        if (err) throw err;
        // delete the temporary file, so that the explicitly set temporary upload dir does not get filled with unwanted files
        fs.unlink(tmp_path, function() {
            if (err) throw err;

        });
    });
});

检索时显示此方法中的路径

fs.readFile(target_path, "binary", function(error, file) {
    if(error) {
      res.writeHead(500, {"Content-Type": "text/plain"});
      res.write(error + "\n");
      res.end();
    } else {

      res.writeHead(200, {"Content-Type": "image/png"});
      res.write(file, "binary");

    }
 });

有关详细信息,请参阅nodejs expressjs upload images and display them