Using PhoneGap FileWriter.write for “big” files

前端 未结 2 1692
夕颜
夕颜 2021-02-04 07:17

I have a problem in my PhoneGap app. I would like to write a file of 15 MB. If I try the OS pulls more and more memory and the app crashes without message. I can reproduce this

2条回答
  •  长情又很酷
    2021-02-04 07:31

    I found the answer.

    Crash reason: PhoneGap FileWrite.write cannot handle too big buffer, do not know exact size, I think this issue is due to PG transfer data to iOS through URL Scheme, somehow it crash when "URL" is too long.

    How to fix it: write small block every time, code below:

    function gotFileWriter(writer) {
      function writeFinish() {
        // ... your done code here...
      }
    
      var written = 0;
      var BLOCK_SIZE = 1*1024*1024; // write 1M every time of write
      function writeNext(cbFinish) {
        var sz = Math.min(BLOCK_SIZE, data.byteLength - written);
        var sub = data.slice(written, written+sz);
        writer.write(sub);
        written += sz;
        writer.onwrite = function(evt) {
          if (written < data.byteLength)
            writeNext(cbFinish);
          else
            cbFinish();
        };
      }
      writeNext(writeFinish);
    }
    

    UPDATE Aug 12,2014:

    In my practice, the performance of saving file through Cordova FileSystem is not good, especially for large file(>5M) on phone, it takes a few seconds. If you are downloading file from server to local disk, you may want a "efficient and direct" way, try cordova-plugin-file-transfer plugin.

提交回复
热议问题