简体   繁体   中英

upload file from cordova file transfer plugin to nodeJS server

I am trying to upload a picture I take from cordova ( cordova plugin file transfer ) to nodeJS server. Here is my mobile app code :

function uploadToServer(pictureName, fileURI) {

  var options = new FileUploadOptions();
  options.fileKey = "file";
  options.mimeType = "image/jpeg";
  options.fileName = pictureName;

  var ft = new FileTransfer();
  ft.upload(fileURI, encodeURI(CONSTANTS.hosts.remoteSR),
    function (res) {
      console.log("Code = " + res.responseCode);
    },
    function (error) {
      $log.debug(error)
      alert("An error has occurred: Code = " + error.code);
    },
    options);

}

PS : fileURI and pictureName are valide params and tested withinother functions correctly.

My node JS server Code :

var express =   require("express");
var multer  =   require('multer');
var app         =   express();

var storage =   multer.diskStorage({
  destination: function (req, file, callback) {
    callback(null, './uploads');
  },
  filename: function (req, file, callback) {
    callback(null, file.fieldname + '-' + Date.now());
  }
});
var upload = multer({ storage : storage}).single('userPhoto');

app.get('/',function(req,res){
  res.sendFile(__dirname + "/index.html");
});

app.post('/api/photo',function(req,res){
  upload(req,res,function(err) {
    if(err) {
      console.log(err)
      return res.end("Error uploading file.");
    }

    res.end("File is uploaded");
  });
});

app.listen(3000,function(){
  console.log("Working on port 3000");
});

PS : the upload is working fine when i upload from other sources. (from for example the index.html upload form)

What happens when I execute the code : "Code= 200" which means upload success but somehow I don't find my file uploaded.

Question : how to plug correctly cordova file transfert pllugin with nodeJS

Node version : 4.4.7 Cordova Version : 6.x

ok I found it :

options.fileKey = "file";  

should match

multer({ storage : storage}).single('userPhoto');

so options.fileKey should be set to userPhoto like this

options.fileKey = "userPhoto";  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM