我尝试使用node.js将文件上传到aws,但我不知道我的代码出了什么问题

时间:2017-11-01 02:14:33

标签: javascript node.js body-parser multer-s3

  1. app.js文件:

    var aws = require('aws-sdk'),
        http = require('http'),
        bodyParser = require('body-parser'),
        fs = require('fs'),
        path = require('path'),
        methodOverride = require("method-override"),
        express = require('express');
    
    var app = new express();
    
    app.set('views', __dirname + '/views');
    app.set('view engine', 'jade');
    app.use(bodyParser.urlencoded({extended: true}));
    app.use(bodyParser.json());
    app.use(express.static(path.join(__dirname, 'public')));
    app.use(methodOverride("_method"));
    
    var config_path = path.join(__dirname, 'auth.json');
    
    aws.config.loadFromPath(config_path);
    var s3 = new aws.S3();
    
    app.get('/buckets', function(req, res){
      s3.listBuckets(function (err, data) {
        res.json(data);
      });
    
    });
    
    app.get('/upload', function (req, res) {
      res.render('upload');
    });
    
    app.post('/upload', function (req, res) {
      var s3request = {
        Body: fs.readFileSync(req.files.theFile.path),
        Bucket: 'bucket-*********',
        Key: req.files.theFile.name
        };
    
    s3.putObject(s3request, function (err, data) {
        res.render('upload', {done: true});
      });
    });
    
    const PORT = process.env.PORT || 5000;
    app.listen(PORT);
    
    module.exports = app;
    
  2. layout.jade:

    doctype html
    html
      head
        title intra
        link(rel='stylesheet', href='/css/bootstrap.min.css')
      body
        block content
    
  3. upload.jade:

    extends layout
    
    block content
      div.container
        if (done)
          p Upload complete
        h3 Upload File
        form(enctype="multipart/form-data", method="post")
         label Photo:
            p
              input(type="file", name="theFile")
            input(type="submit", value="Submit")
    
  4. 运行。 TypeError:无法读取属性' theFile'未定义的。

1 个答案:

答案 0 :(得分:1)

我没有运行任何测试来确认,但是通过查看代码,我发现您正在尝试访问数组。

Key: req.files.theFile.name

req.files是一个数组,因此您可能希望将代码重构为:

Key: req.files[0].name

假设您只上传了一个文件。

您可以使用此示例作为参考 http://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/s3-example-photo-album.html