Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
666 views
in Technique[技术] by (71.8m points)

express - How to get direct URL to multipart file uploaded via Node.js

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

(Multer NPM) has already written there in documentation:

.single(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]) ????=> (req.files)

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);
});

.fields(fields) ????=> (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);
});

.any() ????=> (req.files)

Accepts all files that comes over the wire. An array of files will be stored in req.files.

.none()

Accept only text fields. If any file upload is made, error with code "LIMIT_UNEXPECTED_FILE" will be issued.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...