我正在尝试学习AWS S3,所以我正在构建一个用于上传的表单,之后用于下载我上传的图片。
目前,如果我上传的图片在应用的同一目录下,一切都能正常工作。它将出现在我的S3桶中。但是如果我尝试从其他目录上传图片,我就会得到这个错误。
Error: ENOENT: no such file or directory, open 'myphoto.jpg'
at Object.openSync (fs.js:443:3)
at Object.readFileSync (fs.js:343:35)
at uploadFile (/home/morbi/bucketTest/upload.js:14:26)
at /home/morbi/bucketTest/app.js:65:3
at Layer.handle [as handle_request] (/home/morbi/bucketTest/node_modules/express/lib/router/layer.js:95:5)
at next (/home/morbi/bucketTest/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/home/morbi/bucketTest/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/home/morbi/bucketTest/node_modules/express/lib/router/layer.js:95:5)
at /home/morbi/bucketTest/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/home/morbi/bucketTest/node_modules/express/lib/router/index.js:335:12)
这是我的表单,这是一个非常简单的测试用表单,index.ejs。
<html>
<head>
<title>Bucket Test</title>
</head>
<body>
<a href="/bucket">Create Bucket</a>
<form action="/" method="POST">
<label for="img">Select image:</label>
<input type="file" id="img" name="img" accept="image/*">
<input type="submit">
</form>
</body>
</html>
这是我的app. js:
// load .env data into process.env
require('dotenv').config();
// Web server config
const PORT = process.env.PORT || 8080;
const ENV = process.env.ENV || "development";
const AWS = require('aws-sdk');
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const uploadFile = require("./upload.js");
// Enter copied or downloaded acess ID and secret key here
const ID = process.env.BUCKET_ID;
const SECRET = process.env.BUCKET_SECRET;
// The name of the bucket that you have created
const BUCKET_NAME = process.env.BUCKET_NAME;
const BUCKET_AREA = process.env.BUCKET_AREA;
const s3 = new AWS.S3({
accessKeyId: ID,
secretAccessKey: SECRET
});
const params = {
Bucket: BUCKET_NAME
};
app.use(bodyParser.urlencoded({extended: true}));
app.set("view engine", "ejs");
app.use(express.static(__dirname + "/public"));
app.get("/", function(req,res){
res.render("index");
});
app.get("/bucket", function(req,res){
let string;
s3.createBucket(params, function(err, data){
if (err) {
console.log(err, err.stack);
} else {
string = data.location;
console.log('Bucket Created Successfully', data.location);
}
});
res.render("bucket", {string: string});
});
app.get("/upload", function(req, res){
console.log(req.body);
// let img = req.body;
res.render("download");
});
app.post("/", function(req,res){
let item = req.body.img;
console.log(item);
uploadFile(item);
res.redirect("upload", /* {item: item} */);
});
app.listen(PORT, process.env.IP, function(){
console.log(`Example app listening on port ${PORT}`);
});
这里是我的upload. js:
const fs = require('fs');
const AWS = require('aws-sdk');
const BUCKET_NAME = process.env.BUCKET_NAME;
const ID = process.env.BUCKET_ID;
const SECRET = process.env.BUCKET_SECRET;
const s3 = new AWS.S3({
accessKeyId: ID,
secretAccessKey: SECRET
});
const uploadFile = (fileName) => {
// Read content from the file
const fileContent = fs.readFileSync(fileName);
// Setting up S3 upload parameters
const params = {
Bucket: BUCKET_NAME,
Key: fileName, // File name you want to save as in S3
Body: fileContent
};
// Uploading files to the bucket
s3.upload(params, function(err, data) {
if (err) {
throw err;
} else {
console.log(`File uploaded successfully. ${data.location}`);
}
});
};
module.exports = uploadFile;
我假设它不能工作的原因是 当我选择fileimage的时候 它只传递了文件名而不是路径 那么我如何将路径附加到文件上呢?
我想明白了,在youtube上看到一些视频,他们使用了Multer和Multer-s3,但我不想改变我的upload.js文件,所以我遇到了express-upload包,在我的app目录下创建了一个文件夹,在将图片发送到我的bucket之前,将它们转移,一切都很好。
下面是我更新的文件。
app. js:
// load .env data into process.env
require('dotenv').config();
// Web server config
const PORT = process.env.PORT || 8080;
const ENV = process.env.ENV || "development";
const AWS = require('aws-sdk');
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const uploadFile = require("./upload.js");
const fileUps = require('express-fileupload');
// Enter copied or downloaded acess ID and secret key here
const ID = process.env.BUCKET_ID;
const SECRET = process.env.BUCKET_SECRET;
// The name of the bucket that you have created
const BUCKET_NAME = process.env.BUCKET_NAME;
const BUCKET_AREA = process.env.BUCKET_AREA;
const s3 = new AWS.S3({
accessKeyId: ID,
secretAccessKey: SECRET
});
const params = {
Bucket: BUCKET_NAME
};
app.use(bodyParser.urlencoded({extended: true}));
app.set("view engine", "ejs");
app.use(express.static(__dirname + "/public"));
app.use(fileUps());
app.get("/", function(req,res){
res.render("index");
});
app.get("/bucket", function(req,res){
let string;
s3.createBucket(params, function(err, data){
if (err) {
console.log(err, err.stack);
} else {
string = data.location;
console.log('Bucket Created Successfully', data.location);
}
});
res.render("bucket", {string: string});
});
app.get("/upload", function(req, res){
console.log(req.body);
// let img = req.body;
res.render("download");
});
app.post("/", function(req,res){
if(req.files === null) {
return res.status(400).json({ msg: 'No file uploaded' });
}
const file = req.files.img;
file.mv(`${__dirname}/uploads/${file.name}`, function(err) {
if(err) {
console.error(err);
return res.status(500).send(err);
}
});
console.log(file);
uploadFile(file.data ,file.name);
res.redirect("upload", {item: file.name});
});
app.listen(PORT, process.env.IP, function(){
console.log(`Example app listening on port ${PORT}`);
});
和upload. js:
const AWS = require('aws-sdk');
const BUCKET_NAME = process.env.BUCKET_NAME;
const ID = process.env.BUCKET_ID;
const SECRET = process.env.BUCKET_SECRET;
const s3 = new AWS.S3({
accessKeyId: ID,
secretAccessKey: SECRET
});
const uploadFile = (fileData, fileName) => {
// Read content from the file
const fileContent = fileData;
// Setting up S3 upload parameters
const params = {
Bucket: BUCKET_NAME,
Key: fileName, // File name you want to save as in S3
Body: fileContent
};
// Uploading files to the bucket
s3.upload(params, function(err, data) {
if (err) {
throw err;
} else {
console.log(`File uploaded successfully. ${data.location}`);
}
});
};
module.exports = uploadFile;
现在我需要做的就是在上传到s3 bucket后删除uploads文件夹里的文件,这样服务器就不会没有空间了。
希望能帮到其他人。