Multer: How to show the uploaded files on Browser?

Created on 15 Sep 2016  路  9Comments  路  Source: expressjs/multer

I am able to upload my .wav files and the converted mp3 files using ffmpeg converter that convert .wav files to mp3 in uploads folder but can't able to show them on browser. I am using angular js and node js for doing this . I am new to angular and node . Please help? I want to show all the files on browser instead of uploading to uploads folder?

Most helpful comment

Can you share some code so we could help? Maybe StackOverflow is a better place for asking these sort of questions.

All 9 comments

Can you share some code so we could help? Maybe StackOverflow is a better place for asking these sort of questions.

//index.html




<title>wav2mp3</title>

<!-- SCROLLS -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css"><!-- load bootstrap -->
<style>
    html                    { overflow-y:scroll; }
    body                    { padding-top:50px; }
    #todo-list              { margin-bottom:30px; }
    #todo-form              { margin-bottom:50px; }
</style>

<!-- SPELLS -->
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js"></script><!-- load angular -->
<!--<script src="https://code.jquery.com/jquery-1.12.3.js"></script>-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>




mp3 converter






Choose File...
type="file"
ngf-select
ng-model="up.file"
name="file"
ngf-max-size="20MB"
style='position:absolute;z-index:2;top:0;left:0;filter: alpha(opacity=0);-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";opacity:0;background-color:transparent;color:transparent;' size="40" onchange='$("#upload-file-info").html($(this).val());$("#fileN").val($(this).val());'/>

 

        <i ng-show="up.upload_form.file.$error.required">*required</i><br>
        <i ng-show="up.upload_form.file.$error.maxSize">File too large 
        {{up.file.size / 1000000|number:1}}MB: max 20M</i>
       <!--  Multiple files
        <div class="button" ngf-select ng-model="up.files" ngf-multiple="true">Select</div>
        Drop files: <div ngf-drop ng-model="up.files" class="drop-box">Drop</div> -->
        <button class="btn btn-success" type="submit" ng-click="up.submit()">Convert to mp3</button>
        <p>{{up.progress}}</p>
        <br><br>
    <!-- <button class="btn btn-warning" ng-click="up.downloadMP3()">download mp3</button> -->
    </div>
    </form>

    <input id="fileN" type="hidden" ng-model="fileName">

    </div>
</body>
<script type="text/javascript" src="node_modules/angular/angular.min.js"></script>
<script type="text/javascript" src="node_modules/ng-file-upload/dist/ng-file-upload.min.js"></script>
<script type="text/javascript" src="node_modules/ng-file-upload/dist/ng-file-upload-shim.min.js"></script>
<script type="text/javascript" src="main.js"></script>

//main.js (angular modules and controllers)
angular.module('fileUpload', ['ngFileUpload'])
.controller('MyCtrl',['$scope','Upload','$window', '$http', function($scope,Upload,$window,$http){
var vm = this;
vm.submit = function(){ //function to call on form submit
if (vm.upload_form.file.$valid && vm.file) { //check if from is valid
vm.upload(vm.file); //call upload function
}
}

vm.upload = function (file) {
    Upload.upload({
        url: 'http://localhost:3000/upload', //webAPI exposed to upload the file
        data:{file:file} //pass file as data, should be user ng-model
    }).then(function (resp) { //upload function returns a promise
        if(resp.data.error_code === 0){ //validate success
            $window.alert('Success ' + resp.config.data.file.name + 'uploaded. Response: ');
        } else {
            $window.alert('an error occured');
        }
    }, function (resp) { //catch error
        console.log('Error status: ' + resp.status);
        $window.alert('Error status: ' + resp.status);
    }, function (evt) { 
        console.log(evt);
        var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
        console.log('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);
        vm.progress = 'progress: ' + progressPercentage + '% '; // capture upload progress
    });
};

// vm.downloadMP3 = function(){
//     console.log("download");
//     vm.download();
// }

// var fileN = $("#fileN").val();
// console.log(fileN.split('.')[0]);

// vm.download = function(file) {
//     var url = 'http://localhost:3000/download?id='+fileN.split('.')[0];
//     console.log(url);
//     window.open(url);
    /*$http.get('/download?id='+fileN.split('.')[0])
    .success(function(data) {
        console.log("success");
    })
    .error(function(data) {
        console.log('Error: ' + data);
    });*/
// }

}]);

//app.js (node or server or express js)
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var multer = require('multer');

var program = require('commander');
var exec = require('child_process').exec;

var path = require('path');
var mime = require('mime');
var fs = require('fs');

app.use(function(req, res, next) { //allow cross origin requests
    res.setHeader("Access-Control-Allow-Methods", "POST, PUT, OPTIONS, DELETE, GET");
    res.header("Access-Control-Allow-Origin", "http://localhost");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});

/** Serving from the same express Server
No cors required */
app.use(express.static('../client'));
app.use(bodyParser.json());  

var storage = multer.diskStorage({ //multers disk storage settings
    destination: function (req, file, cb) {
        cb(null, './uploads/');
        console.log("######"+file.originalname);
        var destName = file.originalname.split('.')[0]+".mp3";
        var destination_file = "./uploads/"+destName;
        var source_file = "./uploads/"+file.originalname;
        var ffmpeg = 'ffmpeg -i '+ source_file +' -acodec libmp3lame ' + destination_file;
        console.log(destination_file);
        var child = exec(ffmpeg, function(err, stdout, stderr) {
            console.log(' converted to '+ destination_file);
        });
    },
    filename: function (req, file, cb) {
        console.log("filename"+file.fieldname + '-' + datetimestamp + '.' + file.originalname);

        var datetimestamp = Date.now();
        cb(null, file.originalname);
       // cb(null, file.fieldname + '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length -1]);
    }
});

var upload = multer({ //multer settings
                storage: storage
            }).single('file');

/** API path that will upload the files */
app.post('/upload', function(req, res) {
    upload(req,res,function(err){
        if(err){
             res.json({error_code:1,err_desc:err});
             return;
        }

         res.json({error_code:0,err_desc:null});
    });
});



// app.get('/download', function(req, res) {

//         console.log("downloading...."+req.query.id);
//         var path = "./uploads/"+req.query.id+".mp3";

        /*var filename = path.basename(file);

var mimetype = mime.lookup(file);

res.setHeader('Content-disposition', 'attachment; filename=' + filename);
res.setHeader('Content-type', mimetype);

var filestream = fs.createReadStream(file);
filestream.pipe(res);*/

// res.download(path, req.query.id+".mp3", function(err){
// if (err) throw err;
// console.log('popup download save dialog!');

// });

// });

app.listen('3000', function(){
    console.log('running on 3000...');
});

this is the code which is converting .wav file to mp3 using ffmpeg and downloading it in uploads folder but not displaying on browser ? Please help..

Adding this to app.js

app.use('/uploads', express.static(path.join(__dirname, './uploads')))

will make your upload files available under http://localhost:3000/uploads/*.

I added it to app.js but it's not displaying when running local host?
http://localhost:3000/uploads/* when using this it says cannot GET/uploads/

You need to specify the actual file name instead of *, so if your uploaded file is called upload.mp3 it would be http://localhost:3000/uploads/upload.mp3.

Hey, thank you so much for this help .
It's working fine but what to do if I want to display multiple files.

I want all my previously uploaded .wav files and .mp3 files to be displayed and also which I upload recently should be displayed on browser? It means I want previously uploaded files to be visible when running localhost with the recently uploaded files . I want to display all my uploads folder files displayed when running http://localhost:3000 ? Please Help..

I want to display uploads folder files on client side UI I want it for users? Please help..
I tried but not able to do so

I would advise you to post this to StackOverflow since it's not related specifically to multer but more to general Node.js development.

Closing this since, listing files in a directory is outside the scope of multer. Thanks shime for you helpful comments, it's appreciated!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ChristianRich picture ChristianRich  路  4Comments

samipjain picture samipjain  路  4Comments

tonghae picture tonghae  路  4Comments

edi picture edi  路  4Comments

sant123 picture sant123  路  4Comments