Storing the image from an HTML input file form locally

后端 未结 4 1803
忘掉有多难
忘掉有多难 2021-01-05 20:36

I was wondering if it is possible to store the image from


locally. Would I have to store the imag

4条回答
  •  太阳男子
    2021-01-05 21:13

    Contrary to the other answers here, if you're using a modern browser you can get and store quite a bit about the contents of a file using elm.files, FileReader and window.localStorage. You can even tell the browser to save it again (default download behaviour).

    It should be noted that doing this does not mean you can set the .value on the node.

    Here is an example of what you can do, assuming a file has been chosen.

    // From  node
    var elm = document.getElementById('image'),
        img = elm.files[0],
        fileName = img.name, // not path
        fileSize = img.size; // bytes
    
    // By Parsing File
    var reader = new FileReader(),
        binary, base64;
    reader.addEventListener('loadend', function () {
        binary = reader.result; // binary data (stored as string), unsafe for most actions
        base64 = btoa(binary); // base64 data, safer but takes up more memory
    }, false);
    reader.readAsBinaryString(img);
    

    From here you can save in localStorage, create dataURIs etc. For example, Say from fileName we know the image is a .jpg, then you could display it by setting an 's src to "data:image/jpeg;base64," + base64.

    Note that any modification of this data will not have any effect on the original file chosen.

提交回复
热议问题