Using jQuery's ajax method to retrieve images as a blob

前端 未结 3 2214
南旧
南旧 2020-11-22 10:36

I recently asked another (related) question, which lead to this follow up question: Submitting data instead of a file for an input form

Reading through the jQuery.aj

3条回答
  •  萌比男神i
    2020-11-22 11:18

    A big thank you to @Musa and here is a neat function that converts the data to a base64 string. This may come handy to you when handling a binary file (pdf, png, jpeg, docx, ...) file in a WebView that gets the binary file but you need to transfer the file's data safely into your app.

    // runs a get/post on url with post variables, where:
    // url ... your url
    // post ... {'key1':'value1', 'key2':'value2', ...}
    //          set to null if you need a GET instead of POST req
    // done ... function(t) called when request returns
    function getFile(url, post, done)
    {
       var postEnc, method;
       if (post == null)
       {
          postEnc = '';
          method = 'GET';
       }
       else
       {
          method = 'POST';
          postEnc = new FormData();
          for(var i in post)
             postEnc.append(i, post[i]);
       }
       var xhr = new XMLHttpRequest();
       xhr.onreadystatechange = function() {
          if (this.readyState == 4 && this.status == 200)
          {
             var res = this.response;
             var reader = new window.FileReader();
             reader.readAsDataURL(res); 
             reader.onloadend = function() { done(reader.result.split('base64,')[1]); }
          }
       }
       xhr.open(method, url);
       xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
       xhr.send('fname=Henry&lname=Ford');
       xhr.responseType = 'blob';
       xhr.send(postEnc);
    }
    

提交回复
热议问题