简体   繁体   English

如何在会话存储或本地存储中存储文件(txt、pdf 等)?

[英]How to store file(txt, pdf, etc) in session storage or local storage?

I have a simple input box of type file and a button.我有一个简单的文件类型输入框和一个按钮。 I am trying to store the file in the session on click of button so that if page is refreshed it will be in session.我试图在单击按钮时将文件存储在会话中,以便刷新页面时它将处于会话中。 I tried using我尝试使用

 function storeInSession(){ element = document.getElementById('attachments') var file = element.files[0]; sessionStorage.setItem('fileInSession', file) sessionFile = sessionStorage.getItem('fileInSession') }
 <input type="file" id="attachments"> <button onclick="storeInSession()">Upload</button>

Is there any way I can do this?有什么办法可以做到这一点吗?

Storing images存储图像

The idea here is to be able to take an image that has been loaded into the current web page and store it into localStorage.这里的想法是能够获取已加载到当前网页中的图像并将其存储到 localStorage 中。 As we established above, localStorage only supports strings, so what we need to do here is turn the image into a Data URL.正如我们上面建立的,localStorage 只支持字符串,所以我们这里需要做的是将图像转换为数据 URL。 One way to do this for an image, is to load into a canvas element.对图像执行此操作的一种方法是加载到画布元素中。 Then, with a canvas, you can read out the current visual representation in a canvas as a Data URL.然后,使用画布,您可以将画布中的当前视觉表示作为数据 URL 读出。

Let's look at this example where we have an image in the document with an id of “elephant”:让我们看看这个例子,我们在文档中有一个 id 为“elephant”的图像:

// Get a reference to the image element
var elephant = document.getElementById("elephant");

// Take action when the image has loaded
elephant.addEventListener("load", function () {
    var imgCanvas = document.createElement("canvas"),
        imgContext = imgCanvas.getContext("2d");

    // Make sure canvas is as big as the picture
    imgCanvas.width = elephant.width;
    imgCanvas.height = elephant.height;

    // Draw image into canvas element
    imgContext.drawImage(elephant, 0, 0, elephant.width, elephant.height);

    // Get canvas contents as a data URL
    var imgAsDataURL = imgCanvas.toDataURL("image/png");

    // Save image into localStorage
    try {
        localStorage.setItem("elephant", imgAsDataURL);
    }
    catch (e) {
        console.log("Storage failed: " + e);
    }
}, false); 

您可以将二进制数据编码为base64格式,并将其用作字符串

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM