How to send image file from local machine to server using jQuery ajax request

I have a html form with input type = file, I have an API link for storing images in the cloud. In this function, the user can upload a file from their local computer and upload it to the server. The server returns the cloud URL of the uploaded image. In postman, it works fine, but when used with jquery, I can't figure out how. In postman There are several parameters such as filename, tag and employeeID. There is a File button in the file name field and the Data Format checkbox is checked.

This is my jquery code so far

$("#test-btn").on("click", function() {
$.ajax({
  url: 'myURL/external/upload',
  type: 'POST',
  headers: {
    "appID": "some value",
    "version": "some value",
    "empID": "some value",
    "contentType": "application/x-www-form-urlencoded"
  },
  data: new FormData($("#test-form")),
  processData: false,
  contentType: false,
  success: function() {
    console.log(data)
  },
  error: function(e) {
    console.log(e)
  }
});
});
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form enctype="multipart/form-data" method="post" name="upload-image" id="test-form">
  <input type="file" name="filename" />
  <input type="text" name="tag" value="some value" />
  <input type="text" name="empID" value="some value" />
</form>
<button id="test-btn">make</button>
      

Run codeHide result


I have replaced the confidential fields with dummy values.

+3


source to share


1 answer


$("form#test-form").submit(function(){

    var formData = new FormData(this);

    $.ajax({
        url : 'myURL/external/upload',
        type : 'POST',
        data: formData,
        async: false,
        // your other config, params
        success : function(){console.log(data)},
        error : function(e){console.log(e)}
    });

    return false;
});

      

or you can try:



<form enctype="multipart/form-data" method="post" name="upload-image" id="test-form" action="myURL/external/upload">
  <input type="file" name="filename" />
  <input type="text" name="tag" value="some value" />
  <input type="text" name="empID" value="some value" />
</form>
<button id="test-btn">make</button>

$("form#test-form").submit(function() {
    var formData = new FormData($(this)[0]);
    $.post($(this).attr("action"), formData, function() {
        // success    
    });
    return false;
});

      

0


source







All Articles