Any server side (Node.js) implementation for file uploading?


#1

As I know cordova-file-transfer plugin is for uploading files and a Node.js plugin called multer is available. But multer only shows a method to upload file from a form. The is not available in mobile. I’d like to know if there any server implementation example which can be used for cordova-file-transfer? Thanks.


#2

I found req.body is {}, req.file is undfined by cordova-file-transfer . My code in my ionic side:

var options = new FileUploadOptions()
options.fileKey = "file";
options.fileName = this.thumbnail.substr(this.thumbnail.lastIndexOf('/') + 1)
options.mimeType = "image/jpeg"

var ft = new FileTransfer()
ft.upload(this.thumbnail, encodeURI('http://localhost:3000'),
  (res) => {
    console.log("Code = " + r.responseCode)
    console.log("Response = " + r.response)
    console.log("Sent = " + r.bytesSent)
  },(error) => {
    alert("An error has occurred: Code = " + error.code);
    console.log("upload error source " + error.source);
    console.log("upload error target " + error.target);
  },options)

#3

@zhouhaowowtv Did you find the solution for the server side implementation? Would be great if you helped me out.
Thanks in advance


#4

App
cordova file transfer API call in the app

$cordovaFileTransfer.upload("http://some uri/upload", imageUrlToUpload, options)
        .then(function(result) {
            // Success!
            console.log('upload success');
        }, function(err) {
            // Error
            console.log("error in file upload");
            console.log(err);
        }, function (progress) {
            // constant progress updates
            console.log('some progress')
        });

Node Server code

var multer  =   require('multer');

var storage = multer.diskStorage({
    destination: function (req, file, callBack) {
        callBack(null, 'destinationFolder');
    },

you can also pass in folder name in params to the destination function from the app and access it using req.body
make sure that folder already exists and then pass it to the callBack
you can use normal file functions to check whether folder exists and create it if it doesn’t exist and then pass it to the callBack function

    filename: function (req, file, callBack) {
        callBack(null, 'someName');
    }
});

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

// single(‘file’) - this is the filekey in the options parameter passed in cordova-file-transfer call from app

 app.post('/upload', function (req, res) {
     upload(req, res, function(err) {
         if(err) {
             return res.end("Error uploading file.");
         }
         res.end("File is uploaded");
     });
});