1

I have a link to upload image on a google cloud. I want to allow client to directly upload image to g cloud server. I am using API call for this using jquery ajax method and sending form data through POST. But form data returns undefinded on server side.

On the other hand same thing works fine on postman. In postman header and body key - values are set and are working fine.

This is what API requires:

filename, tag and empID (under the body)

appID, version and empID (under the headers)

this is my code:

HTML

<form method = "post" enctype = "multipart/form-data" id ="test-form">
  <input type="file" name =  "filename"/>
  <input type="text" name = "tag" value = "iwh"/>
  <input type="text" name = "empID" value = "****">
  <input type="submit" value = "button" id = "submit-image-btn"/>
</form>

<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js'></script>

JS

$(document).ready(function(){
  $("form#test-form").submit(function(e){
    var formData = new FormData($(this)[0]);
    console.log(formData);
    $.ajax({
      url : 'companyURL/external/upload',
      type : "POST",
      headers : {
      "appID" : "2",
      "version" : "3",
      "empID" : "****",
      "Content-Type" : "application/x-www-form-urlencoded"
    },
    data : formData,
      cache : false,
      contentType : false,
      processData : false,
      success : function(data){console.log(data)},
      error : function(e){console.log(e)}
    });
    e.preventDefault();
  });
});

On server side (API side) we are using express and multer to handle file upload. When I am checking console on server side it shows all values as undefined (filename : undefined, empID : undefined, tag : undefined).

How do I resolve this issue

Pardeep Dhingra
  • 3,916
  • 7
  • 30
  • 56
Amir Saleem
  • 2,912
  • 3
  • 21
  • 35
  • instead of "headers: porperty" try: `beforeSend: function(request) { request.setRequestHeader("appID", 2); ... }` – Zydnar Jul 13 '17 at 10:45
  • Not sure how NodeJS/Express handles file upload, but I once had a similar problem with PHP and the solution was not obvious: I had to add a `MAX_FILE_SIZE` hidden input. (See [PHP POST method uploads](http://php.net/manual/en/features.file-upload.post-method.php) – even this doc is unclear about this). Check if this changes anything in your case. – Watilin Jul 13 '17 at 10:46
  • This answer I've looked for: https://stackoverflow.com/a/13515414/4392611 may be helpful. – Zydnar Jul 13 '17 at 10:48
  • 1
    Remove the "Content-Type" : "application/x-www-form-urlencoded". – Henrique Oecksler Bertoldi Jul 13 '17 at 10:49
  • I've removed the Contet-Type, still the same error. – Amir Saleem Jul 13 '17 at 11:01
  • @HenriqueOeckslerBertoldi Thank you so much, it is now working. – Amir Saleem Jul 13 '17 at 11:04

0 Answers0