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;
layout.jade:
doctype html
html
head
title intra
link(rel='stylesheet', href='/css/bootstrap.min.css')
body
block content
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")
运行。 TypeError:无法读取属性' theFile'未定义的。
答案 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