Home  >  Q&A  >  body text

Local Storage: A How-To Guide to Saving and Restoring File Objects

<p>I have an application using HTML5/JavaScript which uses </p> <pre class="brush:php;toolbar:false;"><input type="file" accept="image/*;capture=camera" onchange="gotPhoto(this)"></pre> ; <p>To capture camera images. Since my app wants to run offline, how do I save a File (https://developer.mozilla.org/en-US/docs/Web/API/File) object in local storage so that it can be used later Retrieve it when uploading via ajax? </p> <p>I'm getting the file object from...</p> <pre class="brush:php;toolbar:false;">function gotPhoto(element) { var file = element.files[0]; //I want to save 'file' to local storage here :-( }</pre> <p>I can convert the object to a string and save it, but when I restore it it is no longer recognized as a File object and therefore cannot be used to get the file contents. </p> <p>I have a feeling this is unachievable, but I'm open to suggestions. </p> <p>By the way, my workaround was to read the file content while storing and save the complete content to local storage. This works, but quickly consumes local storage since each file is a 1MB+ photo. </p>
P粉253518620P粉253518620395 days ago447

reply all(2)I'll reply

  • P粉005134685

    P粉0051346852023-08-23 12:08:41

    Convert it to base64 and save it.

    function gotPhoto(element) {
       var file = element.files[0];
       var reader = new FileReader()
       reader.onload = function(base64) {
          localStorage["file"] = base64;
       }
       reader.readAsDataURL(file);
    }
    // 保存到本地存储
    
    function getPhoto() {
       var base64 = localStorage["file"];
       var base64Parts = base64.split(",");
       var fileFormat = base64Parts[0].split(";")[1];
       var fileContent = base64Parts[1];
       var file = new File([fileContent], "文件名", {type: fileFormat});
       return file;
    }
    // 获取文件对象

    reply
    0
  • P粉811349112

    P粉8113491122023-08-23 11:45:18

    You cannot serialize File API objects.

    Although this does not solve the specific problem, but... While I haven't used this, if you look at this post there seems to be some way (although not yet supported by most browsers) to store offline image data into some file so that it can be used when the user Restore them while online (without using localStorage)

    reply
    0
  • Cancelreply