I wish to post file to multipart form and upload it to Amazon S3 Bucket and return to user link to the file.
const express = require('express'),
aws = require('aws-sdk'),
bodyParser = require('body-parser'),
multer = require('multer'),
multerS3 = require('multer-s3');
aws.config.update({
secretAccessKey: 'secret',
accessKeyId: 'secret',
region: 'us-east-2'
});
const app = express(),
s3 = new aws.S3();
app.use(bodyParser.json());
const upload = multer({
storage: multerS3({
s3: s3,
bucket: 'some-name',
key: (req, file, cb) => {
console.log(file);
cb(null, file.originalname); //use Date.now() for unique file keys
}
})
});
app.post('/upload', upload.array('file',1), (req, res, next) => {
res.send("How to return File URL?");
});
app.listen(3000);
How can I have the direct URL to the file?
( Multer NPM ) has already written there in documentation:
Accept a single file with the name fieldname. The single file will be stored in req.file .
app.post('/upload', upload.single('file'), (req, res, next) => {
console.log('Uploaded!');
res.send(req.file);
});
Accept an array of files, all with the name fieldname. Optionally error out if more than maxCount files are uploaded. The array of files will be stored in req.files .
app.post('/upload', upload.array('file', 1), (req, res, next) => {
console.log('Uploaded!');
res.send(req.files);
});
Accept a mix of files, specified by fields. An object with arrays of files will be stored in req.files
app.post('/upload', upload.fields([
{ name: 'avatar', maxCount: 1 },
{ name: 'gallery', maxCount: 8 }
]), (req, res, next) => {
console.log('Uploaded!');
res.send(req.files);
});
Accepts all files that comes over the wire. An array of files will be stored in req.files .
Accept only text fields. If any file upload is made, error with code "LIMIT_UNEXPECTED_FILE" will be issued.
U could get it from the location property of the file.
res.send(req.file.location);
Just use
req.file.location
in the Success Response
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.