本文介绍了如何获得直接URL到通过Node.js上传的多部分文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望将文件发布到多部分表单中,然后将其上传到Amazon S3 Bucket,并返回到该文件的用户链接.
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);
如何获得文件的直接URL?
How can I have the direct URL to the file?
推荐答案
( Multer NPM )已在文档中写过:
(Multer NPM) has already written there in documentation:
接受名称为fieldname的单个文件.单个文件将存储在 req.file 中.
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);
});
.array(fieldname [,maxCount])= (必需文件)
接受文件数组,所有文件的名称均为fieldname.如果上传的文件超过maxCount,则可以选择出错.文件数组将存储在 req.files 中.
app.post('/upload', upload.array('file', 1), (req, res, next) => {
console.log('Uploaded!');
res.send(req.files);
});
.fields(fields)==> (必需文件)
接受由字段指定的文件混合.具有文件数组的对象将存储在 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);
});
这篇关于如何获得直接URL到通过Node.js上传的多部分文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!