Local Storage: A How-To Guide to Saving and Restoring File Objects
P粉253518620
P粉253518620 2023-08-22 13:29:16
0
2
411

I have an application using HTML5/JavaScript which uses

;

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?

I'm getting the file object from...

function gotPhoto(element) { var file = element.files[0]; //I want to save 'file' to local storage here :-( }

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.

I have a feeling this is unachievable, but I'm open to suggestions.

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粉253518620
P粉253518620

reply all (2)
P粉005134685

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; } // 获取文件对象
    P粉811349112

    You cannot serialize File API objects.

    Although this does not solve the specific problem, but... While I haven't used this, if you look atthis postthere 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)

      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!