javascript 使用 node.js 上传文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23263307/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 00:38:52  来源:igfitidea点击:

Upload files with node.js

javascriptnode.jsexpress

提问by Or Smith

I have this code in order to upload files with node.js:

我有这个代码是为了用 node.js 上传文件:

    app.use(express.bodyParser());
    // or, as `req.files` is only provided by the multipart middleware, you could 
    // add just that if you're not concerned with parsing non-multipart uploads, 
    // like:
    app.use(express.multipart());

    app.get('/',function(req,res){
    fs.readFile('uploadHTML.html',function (err, data){
        res.writeHead(200, {'Content-Type': 'text/html','Content-Length':data.length});
        res.write(data);
        res.end();
    });

    });
    app.post('/upload',function(req,res)
    {
    console.log(req.files);
    fs.readFile(req.files.displayImage.path, function (err, data) {
      // ...
      var newPath = __dirname;
      fs.writeFile(newPath, data, function (err) {
        res.redirect("back");
      });
    });
 });

Here is the HTML file:

这是 HTML 文件:

<html>
<head>
<title>Upload Example</title>
</head>
<body>

<form id="uploadForm"
      enctype="multipart/form-data"
      action="/upload"
      method="post">
  <input type="file" id="userPhotoInput" name="displayImage" />
  <input type="submit" value="Submit">
</form>

<span id="status" />
<img id="uploadedImage" />


</body>
</html>

When I upload the file, it gives me the next error:

当我上传文件时,它给了我下一个错误:

TypeError: Cannot read property 'displayImage' of undefined at c:\NodeInstall\nodejs\express.js:42:22 at callbacks (c:\NodeInstall\nodejs\node_modules\express\lib\router\index.js:164:37) at param (c:\NodeInstall\nodejs\node_modules\express\lib\router\index.js:138:11) at pass (c:\NodeInstall\nodejs\node_modules\express\lib\router\index.js:145:5) at Router._dispatch (c:\NodeInstall\nodejs\node_modules\express\lib\router\index.js:173:5) at Object.router (c:\NodeInstall\nodejs\node_modules\express\lib\router\index.js:33:10) at next (c:\NodeInstall\nodejs\node_modules\express\node_modules\connect\lib\proto.js:193:15) at Object.expressInit [as handle] (c:\NodeInstall\nodejs\node_modules\express\lib\middleware.js:30:5) at next (c:\NodeInstall\nodejs\node_modules\express\node_modules\connect\lib\proto.js:193:15) at Object.query [as handle] (c:\NodeInstall\nodejs\node_modules\express\node_modules\connect\lib\middleware\query.js:45:5)

What could be the reason?

可能是什么原因?

回答by f1nn

I do recommend you to use awesome module https://github.com/domharrington/fileuploadfor handling file uploads in node/express.

我建议你使用很棒的模块https://github.com/domharrington/fileupload来处理 node/express 中的文件上传。

var fileupload = require('fileupload').createFileUpload('/uploadDir').middleware

app.post('/upload', fileupload, function(req, res) {
  // files are now in the req.body object along with other form fields
  // files also get moved to the uploadDir specified
})

回答by Evalds Urtans

Another way to upload files could be using something like this

上传文件的另一种方法可能是使用这样的东西

Jade template

玉石模板

form.data(action='/user/register', method='post', class="long-fields", enctype='multipart/form-data')
  input(type="text" name="name")
  input(name='fileLogo', type='file')
  input(type="submit" value="Register")

Controller

控制器

formidable = require('formidable'); //file upload handling via form
uuid = require('node-uuid'); //Unique ID
path = require('path'); //Path compiler
fs = require('fs'); //FileSystem

var form = new formidable.IncomingForm();
form.keepExtensions = false;
form.maxFieldsSize = 2 * 1024 * 1024; //2mb

form.parse(req, function(err, fields, files) {

    console.log(fields);
    console.log(files);

    fs.readFile(files.fileLogo.path, function (err, data) {
        var pathNew = __dirname + '/../../uploads/' + uuid.v1() + path.extname(files.fileLogo.name)

        fs.writeFile(pathNew, data, function (err) {
            console.log('uploaded', pathNew);
        });
    });

    res.send(jade.renderFile( settings.pathLess + prefix + '/register.jade', {
        req : req
    }));
});