使用Node.js、Express和Mongoose上传图像 请考虑新的答案,因为这些年来发生了变化,有更多的最新信息。强>

使用Node.js、Express和Mongoose上传图像 请考虑新的答案,因为这些年来发生了变化,有更多的最新信息。强>,node.js,image,file-upload,express,mongoose,Node.js,Image,File Upload,Express,Mongoose,由于许多新的Node.js库很快就会过时,而且我想询问的关于使用以下工具上载图像的示例相对较少: Node.js(v0.4.1) 快车(1.0.7) 猫鼬(1.1.0) 其他人是怎么做到的 我发现:,但我对上传图片还不太熟悉,所以我想学习使用Node.js和Express的一般知识和方法。我将第一次回答我自己的问题。我直接从源头上找到了一个例子。请原谅这个可怜的压痕。我不知道复制和粘贴时如何正确缩进。代码直接来自GitHub上的Express //在中公开模块。/support用于演示目的

由于许多新的Node.js库很快就会过时,而且我想询问的关于使用以下工具上载图像的示例相对较少:

  • Node.js(v0.4.1)
  • 快车(1.0.7)
  • 猫鼬(1.1.0)
其他人是怎么做到的


我发现:,但我对上传图片还不太熟悉,所以我想学习使用Node.js和Express的一般知识和方法。

我将第一次回答我自己的问题。我直接从源头上找到了一个例子。请原谅这个可怜的压痕。我不知道复制和粘贴时如何正确缩进。代码直接来自GitHub上的Express

//在中公开模块。/support用于演示目的
require.path.unshift(_dirname+'/../../support');
/**
*模块依赖关系。
*/
var express=require(“../../lib/express”)
,form=require('connect-form');
var app=express.createServer(
//连接形式(http://github.com/visionmedia/connect-form)
//中间件使用强大的中间件解析URL编码
//和多部分表单数据
表单({keepExtensions:true})
);
app.get('/',函数(req,res){
res.send(“”)
+“图像:

” +“

” + ''); }); app.post(“/”,函数(请求,恢复,下一步){ //连接表单添加req.form对象 //我们可以(可选)定义onComplete,passing //已解析的异常(如果有)字段和已解析的文件 请求表单完成(功能(错误、字段、文件){ 如果(错误){ 下一个(错误); }否则{ console.log('\n将%s添加到%s' ,files.image.filename ,files.image.path); res.redirect(“back”); } }); //我们可以为几个表单添加侦听器 //“进步”等事件 请求表单on('progress',函数(字节接收,字节预期){ var百分比=(字节接收/字节预期*100)| 0; process.stdout.write('上载:%'+percent+'\r'); }); }); app.listen(3000); console.log('Express应用程序在端口3000上启动');
试试这段代码。它会有帮助的

app.get('/photos/new', function(req, res){
  res.send('<form method="post" enctype="multipart/form-data">'
    + '<p>Data: <input type="filename" name="filename" /></p>'
    + '<p>file: <input type="file" name="file" /></p>'
    + '<p><input type="submit" value="Upload" /></p>'
    + '</form>');
});


 app.post('/photos/new', function(req, res) {
  req.form.complete(function(err, fields, files) {
    if(err) {
      next(err);
    } else {
      ins = fs.createReadStream(files.photo.path);
      ous = fs.createWriteStream(__dirname + '/directory were u want to store image/' + files.photo.filename);
      util.pump(ins, ous, function(err) {
        if(err) {
          next(err);
        } else {
          res.redirect('/photos');
        }
      });
      //console.log('\nUploaded %s to %s', files.photo.filename, files.photo.path);
      //res.send('Uploaded ' + files.photo.filename + ' to ' + files.photo.path);
    }
  });
});

if (!module.parent) {
  app.listen(8000);
  console.log("Express server listening on port %d, log on to http://127.0.0.1:8000", app.address().port);
}
app.get('/photos/new',函数(req,res){
res.send(“”)
+“数据:

” +“文件:

” +“

” + ''); }); 应用程序发布('/photos/new',功能(请求、回复){ 请求表单完成(功能(错误、字段、文件){ 如果(错误){ 下一个(错误); }否则{ ins=fs.createReadStream(files.photo.path); ous=fs.createWriteStream(uuu dirname+'/目录是您要存储的image/'+文件.photo.filename); 使用泵(ins、OU、功能(err){ 如果(错误){ 下一个(错误); }否则{ res.redirect('/photos'); } }); //console.log('\n将%s添加到%s',files.photo.filename,files.photo.path); //res.send('上传'+files.photo.filename+'到'+files.photo.path); } }); }); 如果(!module.parent){ app.listen(8000); console.log(“正在端口%d上侦听的Express服务器,登录到http://127.0.0.1:8000,app.address().port); }
您还可以使用以下命令设置保存文件的路径

req.form.uploadDir = "<path>";
req.form.uploadDir=”“;

既然您使用的是express,只需添加bodyParser:

app.use(express.bodyParser());
 /**
 * Module dependencies.
 */

var express = require('express')

var app = express()
app.use(express.bodyParser({ keepExtensions: true, uploadDir: '/home/svn/rest-api/uploaded' }))

app.get('/', function(req, res){
  res.send('<form method="post" enctype="multipart/form-data">'
    + '<p>Image: <input type="file" name="image" /></p>'
    + '<p><input type="submit" value="Upload" /></p>'
    + '</form>');
});

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

    res.send('Uploaded: ' + req.files.image.name)
    return next()

});

app.listen(3000);
console.log('Express app started on port 3000');
然后,您的路由将自动访问req.files中上载的文件:

app.post('/todo/create', function (req, res) {
    // TODO: move and rename the file using req.files.path & .name)
    res.send(console.dir(req.files));  // DEBUG: display available fields
});
如果您将输入控件命名为“todo”(在Jade中):

当您在“files.todo”中获取路径和原始文件名时,上载的文件已准备就绪:

  • req.files.todo.path,以及
  • req.files.todo.name
其他有用的req.files属性:

  • 大小(以字节为单位)
  • 类型(例如,“图像/png”)
  • 最后修改日期
  • _writeStream.encoding(例如,“二进制”)

您可以在主应用程序文件的配置块中配置connect body解析器中间件:

    /** Form Handling */
    app.use(express.bodyParser({
        uploadDir: '/tmp/uploads',
        keepExtensions: true
    }))
    app.use(express.limit('5mb'));

看,你能做的最好的事情就是将图像上传到磁盘,并将URL保存在MongoDB中。再次检索图像时请停止。只需指定URL,您就会得到一个图像。上传代码如下

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;
            //
        });
    });
});
现在将目标路径保存到MongoDB数据库中

同样,在检索图像时,只需从MongoDB数据库中提取URL,并将其用于此方法

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

对于Express 3.0,如果您想使用强大的事件,必须删除多部分中间件,以便创建它的新实例

为此:

app.use(express.bodyParser());
可以写为:

app.use(express.json());
app.use(express.urlencoded());
app.use(express.multipart()); // Remove this line
现在创建表单对象:

exports.upload = function(req, res) {
    var form = new formidable.IncomingForm;
    form.keepExtensions = true;
    form.uploadDir = 'tmp/';

    form.parse(req, function(err, fields, files){
        if (err) return res.end('You found error');
        // Do something with files.image etc
        console.log(files.image);
    });

    form.on('progress', function(bytesReceived, bytesExpected) {
        console.log(bytesReceived + ' ' + bytesExpected);
    });

    form.on('error', function(err) {
        res.writeHead(400, {'content-type': 'text/plain'}); // 400: Bad Request
        res.end('error:\n\n'+util.inspect(err));
    });
    res.end('Done');
    return;
};
我也在我的博客上发表了这篇文章。

我使用了Express和Multer。它非常简单,避免了所有连接警告


它可能会对某人有所帮助。

如果您不想使用bodyParser,请再次执行以下操作:

var express = require('express');
var http = require('http');
var app = express();

app.use(express.static('./public'));


app.configure(function(){
    app.use(express.methodOverride());
    app.use(express.multipart({
        uploadDir: './uploads',
        keepExtensions: true
    }));
});


app.use(app.router);

app.get('/upload', function(req, res){
    // Render page with upload form
    res.render('upload');
});

app.post('/upload', function(req, res){
    // Returns json of uploaded file
    res.json(req.files);
});

http.createServer(app).listen(3000, function() {
    console.log('App started');
});

我知道最初的问题涉及到具体的版本,但它也提到了“最新的”-@JohnAllen的帖子由于

这演示了易于使用的内置bodyParser():

/**
*模块依赖关系。
*/
var express=require('express')
var app=express()
use(express.bodyParser({keepExtensions:true,uploadDir:'/home/svn/restapi/upload'}))
app.get('/',函数(req,res){
res.send(“”)
+“图像:

” +“

” + ''); }); app.post(“/”,函数(请求,恢复,下一步){ res.send('上传:'+req.files.image.name) 返回下一个() }); app.listen(3000); console.log('Express应用程序在端口3000上启动');
以下是一种使用强大软件包上传图像的方法,在更高版本的Express中,建议使用bodyParser。这还包括动态调整图像大小的功能:

从我的网站:

要点如下:

var express = require("express"),
app = express(),
formidable = require('formidable'),
util = require('util')
fs   = require('fs-extra'),
qt   = require('quickthumb');

// Use quickthumb
app.use(qt.static(__dirname + '/'));

app.post('/upload', function (req, res){
  var form = new formidable.IncomingForm();
  form.parse(req, function(err, fields, files) {
    res.writeHead(200, {'content-type': 'text/plain'});
    res.write('received upload:\n\n');
    res.end(util.inspect({fields: fields, files: files}));
  });

  form.on('end', function(fields, files) {
    /* Temporary location of our uploaded file */
    var temp_path = this.openedFiles[0].path;
    /* The file name of the uploaded file */
    var file_name = this.openedFiles[0].name;
    /* Location where we want to copy the uploaded file */
    var new_location = 'uploads/';

    fs.copy(temp_path, new_location + file_name, function(err) {  
      if (err) {
        console.error(err);
      } else {
        console.log("success!")
      }
    });
  });
});

// Show the upload form 
app.get('/', function (req, res){
  res.writeHead(200, {'Content-Type': 'text/html' });
  /* Display the file upload form. */
  form = '<form action="/upload" enctype="multipart/form-data" method="post">'+ '<input name="title" type="text" />
  '+ '<input multiple="multiple" name="upload" type="file" />
  '+ '<input type="submit" value="Upload" />'+ '</form>';
  res.end(form); 
}); 
app.listen(8080);
var express=require(“express”),
app=express(),
强大=需要(“强大”),
util=require('util')
fs=需要('fs-extra'),
qt=需要('quickthumb');
//使用快速拇指
应用程序使用(qt.sta
var express = require("express"),
app = express(),
formidable = require('formidable'),
util = require('util')
fs   = require('fs-extra'),
qt   = require('quickthumb');

// Use quickthumb
app.use(qt.static(__dirname + '/'));

app.post('/upload', function (req, res){
  var form = new formidable.IncomingForm();
  form.parse(req, function(err, fields, files) {
    res.writeHead(200, {'content-type': 'text/plain'});
    res.write('received upload:\n\n');
    res.end(util.inspect({fields: fields, files: files}));
  });

  form.on('end', function(fields, files) {
    /* Temporary location of our uploaded file */
    var temp_path = this.openedFiles[0].path;
    /* The file name of the uploaded file */
    var file_name = this.openedFiles[0].name;
    /* Location where we want to copy the uploaded file */
    var new_location = 'uploads/';

    fs.copy(temp_path, new_location + file_name, function(err) {  
      if (err) {
        console.error(err);
      } else {
        console.log("success!")
      }
    });
  });
});

// Show the upload form 
app.get('/', function (req, res){
  res.writeHead(200, {'Content-Type': 'text/html' });
  /* Display the file upload form. */
  form = '<form action="/upload" enctype="multipart/form-data" method="post">'+ '<input name="title" type="text" />
  '+ '<input multiple="multiple" name="upload" type="file" />
  '+ '<input type="submit" value="Upload" />'+ '</form>';
  res.end(form); 
}); 
app.listen(8080);
router.post('/upload', function(req , res) {

var multiparty = require('multiparty');
var form = new multiparty.Form();
var fs = require('fs');

form.parse(req, function(err, fields, files) {  
    var imgArray = files.imatges;


    for (var i = 0; i < imgArray.length; i++) {
        var newPath = './public/uploads/'+fields.imgName+'/';
        var singleImg = imgArray[i];
        newPath+= singleImg.originalFilename;
        readAndWriteFile(singleImg, newPath);           
    }
    res.send("File uploaded to: " + newPath);

});

function readAndWriteFile(singleImg, newPath) {

        fs.readFile(singleImg.path , function(err,data) {
            fs.writeFile(newPath,data, function(err) {
                if (err) console.log('ERRRRRR!! :'+err);
                console.log('Fitxer: '+singleImg.originalFilename +' - '+ newPath);
            })
        })
}
})
"img": new Buffer.from(fs.readFileSync(req.file.path)).toString("base64")
       let resultHandler = function (err) {
            if (err) {
                console.log("unlink failed", err);
            } else {
                console.log("file deleted");
            }
        }

        fs.unlink(req.file.path, resultHandler);
 `multer const multer = require('multer');
  const upload = multer({ dest: __dirname + '/uploads/images' });`
  Add upload.single('img') in your request

  router.post('/fellows-details', authorize([Role.ADMIN, Role.USER]), 
        upload.single('img'), usersController.fellowsdetails);
    let Id = req.body.id;
    let path = `tmp/daily_gasoline_report/${Id}`;
 const multer = require('multer');
 let fs = require('fs-extra');

 let storage = multer.diskStorage({
 destination: function (req, file, cb) {
    let Id = req.body.id;
    let path = `tmp/daily_gasoline_report/${Id}`;
    fs.mkdirsSync(path);
    cb(null, path);
 },
 filename: function (req, file, cb) {
    // console.log(file);

  let extArray = file.mimetype.split("/");
  let extension = extArray[extArray.length - 1];
  cb(null, file.fieldname + '-' + Date.now() + "." + extension);
 }
})

let upload = multer({ storage: storage });

let createUserImage = upload.array('images', 100);

let multerHelper = {
     createUserImage,
}

   module.exports = multerHelper;
   const multerHelper = require("../helpers/multer_helper");

   router.post(multerHelper. createUserImage , function(req, res, next) {
      //Here accessing the body datas.
    })