【问题标题】:Upload file to Node.js with HTML使用 HTML 将文件上传到 Node.js
【发布时间】:2017-03-21 20:52:39
【问题描述】:

我正在尝试制作一个 API 来使用 Node.js 服务器上传文件。我收到了undefined 的回复。

我正在关注这个教程https://www.youtube.com/watch?v=UtfZ-5WKpro

Node.js:

var express = require('express');

var app = express();
var bodyParser = require('body-parser');

app.use(bodyParser.json());

app.post("*", function(req, res) {
  res.end(JSON.stringify(req.files) + "\n");
});

console.log("Server at 8080");
app.listen(8080);

HTML

<html>
  <head>
    <form method="post"
          enctype="multipart/form-data"
          action="http://localhost:8080">
      <input type="file" name="myimage" />
      <input type="submit" name="submit" value="submit"/>
    </form>
  </head>
</html>

点击提交后,我收到了undefined 回复。

【问题讨论】:

    标签: javascript html node.js file upload


    【解决方案1】:
    bodyParser.json()
    

    ...所以您已经为 JSON 格式的请求设置了解析器

     enctype="multipart/form-data"
    

    …但您没有发出 JSON 格式的请求。

    the documentation for body-parser:

    这不处理多部分实体,因为它们复杂且通常很大。对于多部分正文,您可能对以下模块感兴趣:

    …后面是建议列表。

    选择一个可以处理多部分请求的模块并使用它来代替您当前的选择。

    【讨论】:

      【解决方案2】:

      我建议您使用this module 在 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
      });
      

      另一种上传文件的方法是使用类似的方法

      翡翠模板

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

      控制器

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

      【讨论】:

        猜你喜欢
        • 2016-06-23
        • 2016-02-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-13
        • 1970-01-01
        • 2021-10-19
        • 2018-02-02
        相关资源
        最近更新 更多