0

I'm trying to upload the file to server. currently I'm uploading images. This is my client side code

 onClickfileupload(){
    let data={};
    let path="";
   let api_url = '/api/uploadFileFromIonicHome';
    this.fileChooser.open()
    .then(uri => 
    { 
      path= JSON.stringify(uri);
      alert(path);

   data={
      userEmail: this.userEmail,
      userName: this.userName,
      userRole: this.userRole,
      fileComment: this.desc,
      type: "file",
      fullFileName:'file-'+Date.now()+'.jpg'
  } 
  this.imagesProvider.uploadImage(path, data, api_url).then((res) => {
    let dataPassedBackObj = {
      reload: true,
      pathOfFile: path,
      typeOf: "picture",
      userName: this.userName, 
      fileComment: this.desc
    }
    alert("Successfully uploaded picture...");
    this.events.publish('toggleMenu');

  }, err => {
    alert(err.http_status);

    alert("There was error in uploading picture...");

  }); })
    .catch(e => alert(e));
    }

This is my provider what I'm using to upload the file to server side. This is my providers code

     uploadImage(img, data ,api_url) {
    alert("Uploading file...");
    // Destination URL
    let url = SERVER_HOST + api_url;
    // File for Upload
    var targetPath = img;
    console.log("line 28"+targetPath);
    var options: FileUploadOptions = {
      fileKey: 'image',
      chunkedMode: false,
      mimeType: 'multipart/form-data',
      params: data,
    };

    const fileTransfer: FileTransferObject = this.transfer.create();

    return fileTransfer.upload(targetPath, url, options);
  }

This is my server side code where I'm getting the routes. but req. body is coming empty {}. This is part of my server side code

app.post('/api/uploadFileFromIonicHome', uploadFromHome.single('image'), function(req, res) {
console.log('within /api/uploadFileFromIonicHome');
console.log(req.body.type);
console.log(req.body);
var userName = req.body.userName;
var userEmail = req.body.userEmail;
var userType = req.body.userRole;
var fileName = req.body.fileName;
var type = req.body.type;   
var comment = req.body.comment;
var fileComment = req.body.fileComment;

I'm getting empty "req.body" and "req.body.type is undefined." This the error I'm getting typeerror:cannot convert object to primitive value

Prashant
  • 55
  • 3
  • 9

1 Answers1

0

Use connect-multiparty to read files. Reference link

var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();

app.post('/upload', multipartMiddleware, function(req, resp) {
  console.log(req.body, req.files);
  // don't forget to delete all req.files when done
});
IftekharDani
  • 3,619
  • 1
  • 16
  • 21