如何使用JavaScript将文件存储在浏览器中 [英] How to store file in a browser using JavaScript

查看:164
本文介绍了如何使用JavaScript将文件存储在浏览器中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为网站原型(仅基于浏览器)工作。有一部分我需要上传一些文件。在这里我使用的是JavaScript和HTML。

无论何时用户想要上传(像应用程序中的浏览按钮)一些文件,然后它将可用于下一次。我无法做到这一点。



问题我们可以使用JavaScript / HTML保存/存储/上传文件在浏览器中(不是服务器)??

谢谢 解决方案

将文件直接下载到用户的文件系统中



如果通过保存/存储直接指向用户的计算机/文件系统,则no,由于安全原因,这是不可能的。 / p>

但是,您可以发起下载,这将弹出另存为类型的请求者并允许用户接受或拒绝下载文件。



有多种方法可以启动下载。一个有趣的是锚标记的新<下载 属性您可以在其中指定一个文件名,并自动启动将其 href 的下载设置为

 < / p> 

a href =urlToFiledownload =myFile.ext>点击下载< / a>



本地存储机制



想要在本地保存文件,您可以使用许多本地存储机制之一,例如:


  • 文件系统API (仅在 Chrome目前和Opera的新版本在草稿状态下) 索引DB (允许Blob对象。良好的支持

  • Web SQL (已弃用,但广泛使用

  • Web存储非常好的支持,但只有s tores字符串和空间有限,对象可以保存为JSON字符串)


    请注意,所有这些都是沙盒式的,只有可用的在浏览器中使用与之相同的原点。数据在任何时候都可能(也可能不会)被丢弃(通过用户或浏览器),因此它们不是一个安全存储(始终保留服务器副本或重新生成数据的方式)。


    I am working for a prototype of website(Only Browser based). There is a part where I need to upload some files.Here I am using JavaScript and HTML.

    Whenever user wants to upload(Like Browse button in applications) some files then it will available for next time.I am unable to do this.

    Question Can we save/store/upload a file using JavaScript/HTML in browser only(Not server )??

    Thanks

    解决方案

    Downloading file directly to user's file-system

    If you by save/store mean directly to user's computer/file system then no, this is not possible due to security reasons.

    However, you can initiate a download which will pop up a "save as" type of requester and allow user to accept or deny to download the file.

    There are more than one way to initiate a download. An interesting one is the new download attribute for the anchor tag where you can specify a file name as well as automatically initiate the download setting its href to a data-uri or something else you want to reference for download:

    <a href="urlToFile" download="myFile.ext">Click to download</a>
    

    Local storage mechanisms

    If you simply want to save the file locally you can use one of the many local storage mechanisms such as:

    Note that all of these as sand-boxed and only available in the browser using the same origin as they was written from. The data may or may not be discarded at any point as well (by user or by browser) so they are not a "safe" storage (always keep a server copy or a way to regenerate the data).

    这篇关于如何使用JavaScript将文件存储在浏览器中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆