zoukankan      html  css  js  c++  java
  • ExpressJS File Uploading – GridFS – MongoDB

    n this blog post we will see how to handle multipart data/file uploading with expressjs. Save files to mongodb using GridFS and rending files.

    To handle file uploads in express, i will use the library located at https://github.com/expressjs/multer

     
    $ npm install multer --save

    In your express app.js file

     
    var app = express();
    app.use('/uploads', express.static(__dirname + "/uploads"));
    app.use(multer({dest: './uploads/'}))

    The above code catches all multipart data, fileuploads automatically and stores the file to ‘uploads/’ folder. So its super easy. So basically if you have a form tag, with its action pointed to a express route. Fileupload server handling is taken care automatically and all file move to ‘uploads’ folder.

    Now let’s see how to save uploaded file to mongodb. Detailed explanation of using gridfs here

    Suppose the file upload URL is http://127.0.0.1:3000/upload

     
    var fs = require('fs');
    var mongoose = require('mongoose');
    router.all('/upload',function(req,res){
         var dirname = require('path').dirname(__dirname);
         var filename = req.files.file.name;
         var path = req.files.file.path;
         var type = req.files.file.mimetype;
          
         var read_stream =  fs.createReadStream(dirname + '/' + path);
     
         var conn = req.conn;
         var Grid = require('gridfs-stream');
         Grid.mongo = mongoose.mongo;
     
         var gfs = Grid(conn.db);
          
         var writestream = gfs.createWriteStream({
            filename: filename
        });
         read_stream.pipe(writestream);
            
    });

    Now let’s see how to view image file uploaded in mongo

    If URL to view files is http://127.0.0.1:3000/file/mongo_id

     
    router.get('/file/:id',function(req,res){
          var pic_id = req.param('id');
          var gfs = req.gfs;
     
           gfs.files.find({filename: pic_id}).toArray(function (err, files) {
     
            if (err) {
                res.json(err);
            }
            if (files.length > 0) {
                var mime = 'image/jpeg';
                res.set('Content-Type', mime);
                var read_stream = gfs.createReadStream({filename: pic_id});
                read_stream.pipe(res);
            else {
                res.json('File Not Found');
            }
        });
    });
  • 相关阅读:
    注意 定义类的时候 不要null 别忘了new 实例化 否则报错
    如果通过key获取dictionary里面的value
    C#邮箱身份验证
    时间选择器 可以选择日期和时间
    C#的Timer解析
    使用微软的组件发邮件
    将html代码写入临时文件夹下面的 然后发来给webbrowser使用
    c#中DataGridView 如何设置 才能选中一行 设置鼠标事件
    lumisoft 获取邮件的方法
    C# 动态添加CheckedListBox的选项,并设置选项为 选中? 怎么做?
  • 原文地址:https://www.cnblogs.com/adjk/p/5112322.html
Copyright © 2011-2022 走看看