如何从multer访问上传的文件? [英] How to access uploaded file from multer?

查看:228
本文介绍了如何从multer访问上传的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以将图像上传到 S3 。现在,如果选择的文件是 .gif ,我想要将 .gif 文件转换为 .mp4 并将转换的文件上传到 S3 。我可以将 .gif 转换为 .mp4 ffmpeg 只有当我给出文件的路径。如何从 Multer 访问上传的文件?以下是我的代码:

Im able to upload an image to S3. Now, if the file selected is .gif, I want to be able to convert the .gif file to .mp4 and upload the converted file to S3. I am able to convert a .gif to .mp4 with ffmpeg only if I give the path of the file. How do I access the uploaded file from Multer? Below is my code :

var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var aws = require('aws-sdk');
var multer = require('multer');
var multerS3 = require('multer-s3');
var s3 = new aws.S3();
var ffmpeg = require('fluent-ffmpeg');


var upload = multer({
    storage: multerS3({
        s3: s3,
        bucket: 'myBucket',
        key: function (req, file, cb) {
            console.log(file);
            var extension = file.originalname.substring(file.originalname.lastIndexOf('.')+1).toLowerCase();

                if(extension=="gif"){
                console.log("Uploaded a .gif file");

                ffmpeg(file) //THIS IS NOT WORKING
                    .setFfmpegPath("C:\\ffmpeg\\bin\\ffmpeg.exe")
                      .output('./outputs/2.mp4')    //TRYING TO UPLOAD LOCALLY, WHICH FAILS
                      .on('end', function() {
                        console.log('Finished processing');
                      })
                      .run();
            }

            cb(null, filename);
        }
    })
});

我正在尝试访问上传的文件,如下所示: ffmpeg(file )因为文件是在 multer 函数中传递的参数。

I'm trying to access the uploaded file like this: ffmpeg(file) since file is an argument passed in the multer function.

我的表单:

<form action="/upload" method="post"  enctype="multipart/form-data">
    <input type="file" name="file"> <br />
    <input type="submit" value="Upload">
</form>

我在哪个部分进行转换?

In which part of the process do I convert the file?

请帮忙。非常感谢。

推荐答案

您正在尝试在本地处理 s3 。该文件需要是您的服务器的文件系统,或至少在 s3 上公开发布。所以你有两个选择。

You are trying to process a file locally that's on s3. The file needs to be your server's file system or at the very least be publicly available on s3. So you have two options here.

a)您可以先将所有文件上传到快速运行的服务器( s3 ,首先我们暂时存储它们)。如果文件是 .gif ,请处理并上传生成的 .mp4 文件,否则上传到 S3 。这是一个工作示例:

a) You could first upload all the files to the server where express is running (not on s3, first we store them temporarily). If the file is a .gif, process it and upload the resulting .mp4 file, otherwise upload to s3. Here's a working example:

var fs         = require('fs')
var path       = require('path')
var express    = require('express');
var bodyParser = require('body-parser');
var aws        = require('aws-sdk');
var multer     = require('multer');
var ffmpeg     = require('fluent-ffmpeg');
var shortid    = require('shortid');


aws.config.update(/* your config */);


var app    = express();
var s3     = new aws.S3();
var bucket = 'myBucket';

var upload = multer({
    storage: multer.diskStorage({
        destination: './uploads/',
        filename: function (req, file, cb){
            // user shortid.generate() alone if no extension is needed
            cb( null, shortid.generate() + path.parse(file.originalname).ext);
        }
    })
});


//----------------------------------------------------
app.post('/upload', upload.single('file'), function (req, res, next) {

    var fileInfo = path.parse(req.file.filename);

    if(fileInfo.ext === '.gif'){

        var videoPath = 'uploads/' + fileInfo.name + '.mp4';

        ffmpeg(req.file.path)
            .setFfmpegPath("C:\\ffmpeg\\bin\\ffmpeg.exe")
            .output(videoPath)
            .on('end', function() {
                console.log('[ffmpeg] processing done');
                uploadFile(videoPath, fileInfo.name + '.mp4');
            })
            .run();
    }
    else {
        uploadFile(req.file.path, req.file.filename);
    }

    res.end();
});


//----------------------------------------------------
function uploadFile(source, target){

    fs.readFile(source, function (err, data) {

        if (!err) {

            var params = {
                Bucket      : bucket,
                Key         : target,
                Body        : data
            };

            s3.putObject(params, function(err, data) {
                if (!err) {
                    console.log('[s3] file uploaded:');
                    console.log(data);
                    fs.unlink(source); // optionally delete the file
                }
                else {
                    console.log(err);
                }
            });
        }
    });
}


app.listen(3000);

b)另外,如果你确定你的 s3 文件公开,您可以使用 multer-s3 上传它们。由于 ffmpeg 也接受网络位置作为输入路径,您可以将 s3 位置 .gif 文件,然后上传转换的 .mp4 文件:

b) Alternatively if you're ok with making your s3 files public you could upload them all using multer-s3. Since ffmpeg also accepts network locations as input paths you can pass it the s3 location of your .gif files and then upload the converted .mp4 files:

var fs         = require('fs')
var path       = require('path')
var express    = require('express');
var bodyParser = require('body-parser');
var aws        = require('aws-sdk');
var multer     = require('multer');
var ffmpeg     = require('fluent-ffmpeg');
var multerS3   = require('multer-s3');


aws.config.update(/* your config */);


var app    = express();
var s3     = new aws.S3();
var bucket = 'myBucket';

var upload = multer({
    storage: multerS3({
        s3: s3,
        bucket: bucket,
        key: function (req, file, cb) {
            cb(null, file.originalname);
        },
        acl: 'public-read'
    })
});

----------------------------------------------------
app.post('/upload', upload.single('file'), function (req, res, next) {

    var fileInfo = path.parse(req.file.originalname);

    if(fileInfo.ext === '.gif'){

        var videoPath = 'uploads/' + fileInfo.name + '.mp4';

        ffmpeg(req.file.location)
            .setFfmpegPath("C:\\ffmpeg\\bin\\ffmpeg.exe")
            .output(videoPath)
            .on('end', function() {
                console.log('[ffmpeg] processing done');
                uploadFile(videoPath, fileInfo.name + '.mp4');
            })
            .run();
    }

    res.end();
})


//----------------------------------------------------
function uploadFile(source, target){

    fs.readFile(source, 'base64', function (err, data) {

        if (!err) {

            var params = {
                Bucket      : bucket,
                Key         : target,
                Body        : data,
                ContentType : 'video/mp4'
            };

            s3.putObject(params, function(err, data) {
                if (!err) {
                    console.log('[s3] file uploaded:');
                    console.log(data);
                    fs.unlink(source); // optionally delete the file
                }
                else {
                    console.log(err);
                }
            });
        }
    });
}

app.listen(3000);

对于这两个例子,记住创建一个 uploads / 文件夹,并使用您的 aws 配置。

For both examples, remember to create an uploads/ folder and use your aws configuration.

这篇关于如何从multer访问上传的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆