node.js - Node.js中的图片上传

标签 node.js file-upload

我是 Node js 新手,现在我想做图像上传。所以我下载了 Express 框架来处理上传。请帮助我如何在服务器端处理该上传。

我创建了这样的表单,如何在后端 Node 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">

最佳答案

使用此方法上传

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了解更多详情

关于node.js - Node.js中的图片上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12524804/

相关文章:

extjs - 如何让Sencha文件上传字段接受多个文件

android - 浏览和上传功能在 Android 中有效吗?

c# - 使用 AllowMultiple=true 维护 FileUpload 中选定文件的顺序

process - 从 Node.js 中的子进程读取二进制数据

mongodb - 如何在 EC2 环境中使用 node-mongodb-native 在 Node.js 服务器上设置 MongoDB?

php - 在 MySQL 数据库中存储大文件的更好方法?

JQuery 文件上传在单独的 Post 请求中发送每个文件?

node.js - ElasticSearch NodeJS - 聚合项返回多个源属性

javascript - Javascript 循环对象时未定义

javascript - 有没有办法在 node.js 中枚举服务器的所有已知主机名?