I am trying to receive video file and save it on the server with multer

9.2k Views Asked by At

I am trying to receive a video file and save it in the uploads folder with the right extensions using node, express, and multer. I know my video is getting passed to the server correctly but it isn't saving how I would like it. This is my backend code.

var express = require("express");
var bodyParser = require("body-parser");
var multer = require("multer");
var app = express();
var path = require('path'); 

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// this is cors this allows my angular app to call this node backend even though they are both on local host 
app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});
// here I am calling multer to get the filename of the file I am serving up specifying what folder I want it to go in
 var storage = multer.diskStorage({
     destination: function (request, file, callback){
         callback(null, './uploads');
     }, 
     filename: function(request, file, callback){
         console.log(file); 
         callback(null, file.originalname)
     }
 }); 

 var upload = multer({storage: storage}); 
// this app.post calls the post method this is where I will upload the file
 app.post('/upload', function (request, response) {
     upload(request, response, function(err) {
         if(err) {
             console.log('Error Occured'); 
             return; 
         }
         console.log(request.file);
         response.end('Your file Uploaded'); 
         console.log('Video Uploaded'); 
     })
 }); 
// my app is listening on localhost port 8080 for the post to be called
 var server = app.listen(8080, function () {
     console.log('Listening on port ' + server.address().port) 
 }); 

this is my error

c:\toolbox\pos-estate-data\oneops\ScoSopBackend>node app.js
Listening on port 8080
TypeError: upload is not a function
    at c:\toolbox\pos-estate-data\oneops\ScoSopBackend\app.js:29:6
    at Layer.handle [as handle_request] (c:\toolbox\pos-estate-data\oneops\ScoSo
pBackend\node_modules\express\lib\router\layer.js:95:5)
    at next (c:\toolbox\pos-estate-data\oneops\ScoSopBackend\node_modules\expres
s\lib\router\route.js:131:13)

client side code

upLoad() {
    let strSopName : string = (<HTMLInputElement>document.getElementById("sopName")).value; 
    if(strSopName == "" || strSopName == null || strSopName == "Error you must enter a sop name"){
        strSopName = "Error you must enter a sop name"
        return;
    }

    this.makeFileRequest("http://localhost:8080/upload", [], this.filesToUpload).then((result) => {
        console.log(result); 
    }, (error) => {
        console.error(error);
    }); 

}

makeFileRequest(url: string, params: Array<string>, files: Array<File>){
    return new Promise((resolve, reject) => {
        var formData: any = new FormData(); 
        var xhr = new XMLHttpRequest(); 
        for(var i = 0; i < files.length; i++){
            formData.append("uploads[]", files[i], files[i].name); 
        }
        xhr.onreadystatechange = function() {
            if(xhr.readyState == 4){
                if(xhr.status == 200){
                    resolve(JSON.parse(xhr.response));
                }else {
                    reject(xhr.response); 
                }
            }
        }
        xhr.open("POST", url, true); 
        xhr.send(formData); 
    })
}

html

<br>
                <input type="file" (change)="fileChangeEvent($event)" name="videofile" placeholder="upload file..." class="form-control" id="Video" accept="video/mp4, video/x-m4v, video/*" required>
           <br>
1

There are 1 best solutions below

10
On BEST ANSWER

You aren't properly initialising multer's upload middleware. That's why experiencing type error.

In your case, you want to upload single file, try the following initialisation and replace 'file' with input name related to file in form

e.g.,

You have input tag of type="file" with name="videoFile" in form in your html

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

Then, you can initialise multer to pull file

var upload = multer({storage: storage}).single('videoFile');

Please note that it is name of input tag that receives file, not filename itself.

EDIT

As discussed in comments, you are uploading multiple files. Try

var upload = multer({storage: storage}).array('uploads'); 

Hope it helps you.