How to save a image to HTML5 filesystem with the url of image

后端 未结 5 1548
青春惊慌失措
青春惊慌失措 2021-01-03 05:26

I am trying to use HTML5 system to store images of my website, and I find there are many example to show how to store a local image to your chrome file system but I can\'t f

5条回答
  •  粉色の甜心
    2021-01-03 05:57

    The problem is that browser will parse xhr response data as UTF-8, So the point is to override MimeType:

    window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
    
    var xhr = new XMLHttpRequest();
    var photoUrl = 'http://localhost:3000/image.jpg';
    xhr.open('GET', photoUrl, true);
    
    // This stops the browser from parsing the data as UTF-8:
    xhr.overrideMimeType('text/plain; charset=x-user-defined');
    
    function stringToBinary(response) {
      var byteArray = new Uint8Array(response.length);
      for (var i = 0; i < response.length; i++) {
        byteArray[i] = response.charCodeAt(i) & 0xff;
      }
      return byteArray
    }
    
    function onInitFs(fs) {
      xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
          fs.root.getFile('image.jpg', {'create': true}, function(fileEntry) {
            fileEntry.createWriter(function(fileWriter) {
              fileWriter.onwriteend = function(event) {
                $('body').append('');
              }
    
              buffer = stringToBinary(xhr.response);
              var blob = new Blob([ buffer ], { type: 'image/jpeg' } )
    
              fileWriter.write(blob);
            }, errorHandler );
          });
        }
      }
      xhr.send();
    }
    
    var errorHandler = function(err) {
      console.log(err);
    }
    
    $(function() {
      webkitStorageInfo.requestQuota(PERSISTENT, 5*1024*1024, function(grantedBytes) {
        requestFileSystem(PERSISTENT, grantedBytes, onInitFs, errorHandler)
      }, errorHandler)
    })
    

提交回复
热议问题