节点/ Express文件上传

时间:2014-05-16 01:18:00

标签: node.js file-upload express

我正在使用节点v0.10.26并表达v4.2.0而且我对节点很新。在过去三个小时左右的时间里,我一直在我的桌子上打我的头,试图让一个文件上传表格与节点一起工作。在这一点上,我只是想让req.files不返回undefined。我的观点看起来像这样

<!DOCTYPE html>
<html>
  <head>
    <title>{{ title }}</title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
    <h1>{{ title }}</h1>
    <p>Welcome to {{ title }}</p>
        <form method='post' action='upload' enctype="multipart/form-data">
        <input type='file' name='fileUploaded'>
        <input type='submit'>


</form>
  </body>
</html>

这是我的路线

var express = require('express');
var router = express.Router();


/* GET home page. */
router.get('/', function(req, res) {
  res.render('index', { title: 'Express' });
});

router.post('/upload', function(req, res){
console.log(req.files);
});

module.exports = router;

这是我的app.js

var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hjs');

app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);

/// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

/// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});



module.exports = app;

我看到包括methodOverride()bodyParser({keepExtensions:true,uploadDir:path})在内的某个地方应该提供帮助,但如果添加这些行,我甚至无法启动我的服务器。

11 个答案:

答案 0 :(得分:84)

ExpressJS问题:

大多数中间件都是从快递4中删除的。 结帐:http://www.github.com/senchalabs/connect#middleware 对于busboy,busboy-connect,强大,流量等多部分中间件,需要分开。

此示例使用 connect-busboy 中间件。 create / img和/ public文件夹 使用文件夹结构:

\ server.js

\ img \&#34;将内容上传到&#34;

\公共\ index.html的

SERVER.JS

var express = require('express');    //Express Web Server 
var busboy = require('connect-busboy'); //middleware for form/file upload
var path = require('path');     //used for file path
var fs = require('fs-extra');       //File System - for file manipulation

var app = express();
app.use(busboy());
app.use(express.static(path.join(__dirname, 'public')));

/* ========================================================== 
Create a Route (/upload) to handle the Form submission 
(handle POST requests to /upload)
Express v4  Route definition
============================================================ */
app.route('/upload')
    .post(function (req, res, next) {

        var fstream;
        req.pipe(req.busboy);
        req.busboy.on('file', function (fieldname, file, filename) {
            console.log("Uploading: " + filename);

            //Path where image will be uploaded
            fstream = fs.createWriteStream(__dirname + '/img/' + filename);
            file.pipe(fstream);
            fstream.on('close', function () {    
                console.log("Upload Finished of " + filename);              
                res.redirect('back');           //where to go next
            });
        });
    });

var server = app.listen(3030, function() {
    console.log('Listening on port %d', server.address().port);
});

INDEX.HTML

<!DOCTYPE html>
<html lang="en" ng-app="APP">
<head>
    <meta charset="UTF-8">
    <title>angular file upload</title>
</head>

<body>
        <form method='post' action='upload' enctype="multipart/form-data">
        <input type='file' name='fileUploaded'>
        <input type='submit'>
 </body>
</html>

以下内容适用于强大的内容 SERVER.JS

var express = require('express');   //Express Web Server 
var bodyParser = require('body-parser'); //connects bodyParsing middleware
var formidable = require('formidable');
var path = require('path');     //used for file path
var fs =require('fs-extra');    //File System-needed for renaming file etc

var app = express();
app.use(express.static(path.join(__dirname, 'public')));

/* ========================================================== 
 bodyParser() required to allow Express to see the uploaded files
============================================================ */
app.use(bodyParser({defer: true}));
 app.route('/upload')
 .post(function (req, res, next) {

  var form = new formidable.IncomingForm();
    //Formidable uploads to operating systems tmp dir by default
    form.uploadDir = "./img";       //set upload directory
    form.keepExtensions = true;     //keep file extension

    form.parse(req, function(err, fields, files) {
        res.writeHead(200, {'content-type': 'text/plain'});
        res.write('received upload:\n\n');
        console.log("form.bytesReceived");
        //TESTING
        console.log("file size: "+JSON.stringify(files.fileUploaded.size));
        console.log("file path: "+JSON.stringify(files.fileUploaded.path));
        console.log("file name: "+JSON.stringify(files.fileUploaded.name));
        console.log("file type: "+JSON.stringify(files.fileUploaded.type));
        console.log("astModifiedDate: "+JSON.stringify(files.fileUploaded.lastModifiedDate));

        //Formidable changes the name of the uploaded file
        //Rename the file to its original name
        fs.rename(files.fileUploaded.path, './img/'+files.fileUploaded.name, function(err) {
        if (err)
            throw err;
          console.log('renamed complete');  
        });
          res.end();
    });
});
var server = app.listen(3030, function() {
console.log('Listening on port %d', server.address().port);
});

答案 1 :(得分:24)

另一种选择是使用multer,它使用busboy,但更容易设置。

var multer = require('multer');

使用multer并设置上传目的地:

app.use(multer({dest:'./uploads/'}));

在您的视图中创建表单,multer工作需要enctype='multipart/form-data

form(role="form", action="/", method="post", enctype="multipart/form-data")
    div(class="form-group")
        label Upload File
        input(type="file", name="myfile", id="myfile")

然后在您的POST中,您可以访问有关该文件的数据:

app.post('/', function(req, res) {
  console.dir(req.files);
});

可以找到关于此的完整教程here

答案 2 :(得分:20)

这是Mick Cullen的answer的简化版本( gist ) - 部分是为了证明实现它不需要非常复杂;部分是为那些对阅读页面和代码页不感兴趣的人提供快速参考。


您必须让应用使用connect-busboy

var busboy = require("connect-busboy");
app.use(busboy());

在触发它之前,这不会做任何事情。在处理上传的调用中,执行以下操作:

app.post("/upload", function(req, res) {
    if(req.busboy) {
        req.busboy.on("file", function(fieldName, fileStream, fileName, encoding, mimeType) {
            //Handle file stream here
        });
        return req.pipe(req.busboy);
    }
    //Something went wrong -- busboy was not loaded
});

让我们打破这个:

  • 检查是否设置了req.busboy(正确加载了中间件)
  • 您在"file"
  • 上设置了req.busboy听众
  • 您将req的内容传输到req.busboy

在文件监听器中有几个有趣的东西,但真正重要的是fileStream:这是Readable,然后可以像往常一样将其写入文件。

陷阱:您必须处理此可读内容,否则快递将永远不会回复请求,请参阅the busboy API文件部分)。

答案 3 :(得分:4)

我发现这个,简单而有效:

app.post('/upload', function(req, res) {
   if (!req.files)
      return res.status(400).send('No files were uploaded.');

   // The name of the input field (i.e. "sampleFile") is used to retrieve the uploaded file
   let sampleFile = req.files.sampleFile;

   // Use the mv() method to place the file somewhere on your server
   sampleFile.mv('/somewhere/on/your/server/filename.jpg', function(err) {
   if (err)
      return res.status(500).send(err);

   res.send('File uploaded!');
});

express-fileupload

答案 4 :(得分:3)

我需要比其他答案提供更多详细信息(例如,如何将文件写入我在运行时决定的位置?)。希望这对其他人有所帮助:

get connect-busboy:

npm install connect-busboy --save

在您的server.js中,添加以下行

let busboy = require('connect-busboy')

// ... 

app.use(busboy());

// ... 

app.post('/upload', function(req, res) {
    req.pipe(req.busboy);
    req.busboy.on('file', function(fieldname, file, filename) {
        var fstream = fs.createWriteStream('./images/' + filename); 
        file.pipe(fstream);
        fstream.on('close', function () {
            res.send('upload succeeded!');
        });
    });
});

这似乎省略了错误处理,但如果我找到它将会编辑它。

答案 5 :(得分:1)

如果您使用的是Node.js Express和Typescript,这是一个有效的示例,它也适用于javascript,只需将let更改为var,将import更改为include等...

首先导入以下内容,以确保通过运行以下命令来安装强大的软件:

SELECT WA.contacts.county
  , National.zips.county
  , WA.contacts.population 
  , National.zips.population
  , WA.contacts.MA_Penetration 
  , National.zips.MA_Penetration
  , WA.contacts.MA_Eligibles 
  , National.zips.MA_Eligibles
FROM WA.contacts 
JOIN National.zips ON WA.contacts.zipcode = National.zips.zipcode
WHERE state = 'WA';

比导入以下内容:

npm install formidable

然后您的功能就像下面这样:

  import * as formidable from 'formidable';
  import * as fs from 'fs';

答案 6 :(得分:0)

Multer是一个用于处理multipart / form-data的node.js中间件,主要用于上传文件。它写在busboy之上,以实现最高效率。

npm install --save multer


in app.js

    var multer  =   require('multer');
    var storage = multer.diskStorage({
      destination: function (req, file, callback) {
        callback(null, './public/uploads');
      },
      filename: function (req, file, callback) {
        console.log(file);
        callback(null, Date.now()+'-'+file.originalname)
      }
    });

    var upload = multer({storage: storage}).single('photo');

    router.route("/storedata").post(function(req, res, next){

        upload(req, res, function(err) {
          if(err) {
            console.log('Error Occured');
            return;
          }
          var userDetail = new mongoOp.User({
            'name':req.body.name,
            'email':req.body.email,
            'mobile':req.body.mobile,
            'address':req.body.address
          });

          console.log(req.file);

          res.end('Your File Uploaded');
          console.log('Photo Uploaded');

          userDetail.save(function(err,result){
          if (err) {
            return console.log(err)
          }
          console.log('saved to database') 
        })
      })

      res.redirect('/')

    });

答案 7 :(得分:0)

这对我来说是一种更简单的方法:

const express = require('express');
var app = express();
var fs = require('fs');

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

  var file = JSON.parse(JSON.stringify(req.files))

  var file_name = file.file.name

  //if you want just the buffer format you can use it
  var buffer = new Buffer.from(file.file.data.data)

  //uncomment await if you want to do stuff after the file is created

  /*await*/
  fs.writeFile(file_name, buffer, async(err) => {

    console.log("Successfully Written to File.");


    // do what you want with the file it is in (__dirname + "/" + file_name)

    console.log("end  :  " + new Date())

    console.log(result_stt + "")

    fs.unlink(__dirname + "/" + file_name, () => {})
    res.send(result_stt)
  });


});

答案 8 :(得分:0)

数周后试图使此文件上传正确的事情后,个人multer却对我不起作用。然后我切换到了强大的功能,几天后我就可以正常工作了,没有任何错误,包括了多个文件,express和react.js,即使react是可选的。指南如下:https://www.youtube.com/watch?v=jtCfvuMRsxE&t=122s

答案 9 :(得分:0)

async function loadModelViewable(viewer, urn, guid = null) {
    function onDocumentLoadSuccess(doc) {
        if (guid) {
            viewer.loadDocumentNode(doc, doc.getRoot().findByGuid(guid));
        } else {
            viewer.loadDocumentNode(doc, doc.getRoot().getDefaultGeometry());
        }
    }
    function onDocumentLoadFailure(code, message) {
        console.error(message);
    }
    Autodesk.Viewing.Document.load('urn:' + urn, onDocumentLoadSuccess, onDocumentLoadFailure);
}

答案 10 :(得分:0)

在 vanila node 中,我解决了一些问题。只是一个快速上传服务器。不是花哨的快递。可能不是提问者想要的。

const fs = require('fs'),
      http = require('http'),
      port = process.env.PORT || 9000,
      host = process.env.HOST || '127.0.0.1';
//tested on node=v10.19.0, export HOST="192.168.0.103"
http.createServer(function(req, res) {

  // Check if form is submitted and save its content
  if (req.method == "POST") try {
    store_file(req)

  // This is here incase any errors occur
  } catch (err) {
    res.writeHead(404);
    res.end('Server Borked');
    return;
  }

  // respond with a simple html form so they can post more data
  res.writeHead(200, {"content-type":"text/html; charset=utf-8"});
  res.end(`
<form  method="post" enctype="multipart/form-data">
  <input type="file" name="fileUpload">
  <input type="submit" value="Upload">
</form>`);
}).listen(port, host, () => console.dir(`Serving at http://${host}:${port}`));

function store_file(req) {
  // Generate temporary file name
  var temp = 'temp' + Math.floor(Math.random() * 10);

  // This opens up the writeable stream to temporary file
  var writeStream = fs.createWriteStream(temp);

  // This pipes the POST data to the file
  req.pipe(writeStream);

  // After the temporary file is creates, create real file
  writeStream.on('finish', () => {

    reader = fs.readFileSync(temp);
    filename = reader.slice(reader.indexOf("filename=\"") + "filename=\"".length, reader.indexOf('"\r\nContent-Type'));
    hash = reader.slice(0,reader.indexOf('\r\n'));
    content = reader.slice(reader.indexOf('\r\n\r\n') + '\r\n\r\n'.length, reader.lastIndexOf(Buffer.from('\r\n') + hash));

    // After real file is created, delete temporary file
    fs.writeFileSync(filename.toString(), content);
    fs.unlinkSync(temp);
  });
}