Search code examples
javascriptrestweb-servicespostform-data

How can I send the POST request to the other server binding file into formdata


I have a pdf file which is generated into my local server with my server side code. I want to send a request to the another server requesting POST. The post method take parameter as FormData where formdata types

one is string and another is file type.

content-type
form-data
Body
  PDF file (file type)
   string value
  

Is it possible to make the POST request without browsing the file location?


Solution

  • Doing some R&D I have overcome this problem with following some steps, as there is no way to get the file object from the physical location automatically in client side (basically in js) except browsing for security reason.

    1. In my local server I have created a REST service. which response base64 string of the desired file.
    2. Than I call the REST api from my javaScript and as a response I receive the base64 string. And than I convert it into bytes array and than Blob object and than File object.

      base64 string==>bytes array==>Blob object==>File object

      var base64 = this.getpdfFromLocal() //get the base64 string
      var byteArray= this.base64ToByte(base64 );
      var file = this.getFileFromByteArray(byteArray);
      
      //return the byte array form the base64 string
      MyApi.prototype.base64ToByte= function(base64) {
          var binaryString = window.atob(base64);
          var binaryLen = binaryString.length;
          var bytes = new Uint8Array(binaryLen);
          for (var i = 0; i < binaryLen; i++) {
              var ascii = binaryString.charCodeAt(i);
              bytes[i] = ascii;
          }
          return bytes;
      };
      MyApi.prototype.getFileFromByteArray=function(byteArray) {
          var blob = new Blob([byteArray]);
          var file = new File([blob], "resource.pdf");
          return file;
       };
      
    3. Lastly I make from data using file object and send request the another server REST web services.

      var formdata = new FormData();
      formdata.append("some_value", "Some String");
      formdata.append("file", file);
      var url = "http://yoururl.com";
      var result =$.ajax({
          url             : url ,
          type            : 'POST',
          data            : formdata,
          contentType     : false,
          cache           : false,
          processData     : false,
          scriptCharset   : 'utf-8',
          async           : false
      }).responseText;