8wDlpd.png
8wDFp9.png
8wDEOx.png
8wDMfH.png
8wDKte.png

Node/Express 文件上传

Thebest 2月前

97 0

我使用的是 node v0.10.26 和 express v4.2.0,我对 node 还很陌生。过去三个小时里,我一直在绞尽脑汁想办法让文件上传表单与 node 兼容。...

我使用的是 node v0.10.26 和 express v4.2.0,我对 node 还很陌生。过去三个小时里,我一直在绞尽脑汁尝试让文件上传表单与 node 配合使用。目前,我只是试图让 req.files 不返回未定义。我的视图如下所示

<!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}) 应该有所帮助,但如果我添加这些行,我甚至无法启动我的服务器。

帖子版权声明 1、本帖标题:Node/Express 文件上传
    本站网址:http://xjnalaquan.com/
2、本网站的资源部分来源于网络,如有侵权,请联系站长进行删除处理。
3、会员发帖仅代表会员个人观点,并不代表本站赞同其观点和对其真实性负责。
4、本站一律禁止以任何方式发布或转载任何违法的相关信息,访客发现请向站长举报
5、站长邮箱:yeweds@126.com 除非注明,本帖由Thebest在本站《express》版块原创发布, 转载请注明出处!
最新回复 (0)
  • ExpressJS 问题:

    大多数中间件已从 express 4 中删除。请查看: http://www.github.com/senchalabs/connect#middleware ,需要多部分中间件,例如 busboy、busboy-connect、formidable、flow、parted。

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

    \服务器.js

    \img\\'资料上传到哪里\'

    \公共\索引.html

    服务器端

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

    索引.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);
    });
    
返回
作者最近主题: