通过 websocket 接收文件并保存/写入本地文件夹 [英] Receive file via websocket and save/write to local folder

查看:349
本文介绍了通过 websocket 接收文件并保存/写入本地文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们的应用程序完全建立在 websockets 上.我们不做任何 HTTP 请求-回复.但是,我们坚持文件下载.如果我通过 websockets 接收文件内容,我可以写入用户计算机上的本地文件夹吗?

Our application is entirely built on websockets. We don't do any HTTP request-reply. However, we are stuck with file download. If i receive file content via websockets can I wrote to local folder on user computer ?

如果它有所作为,我们只支持 Chrome,因此如果它在其他浏览器上不起作用,则不会出现问题.

If it makes a difference, we are only supporting Chrome so not issue if it doesn't work on other browsers.

另外,我知道我可以通过 HTTP 来做到这一点.试图避免它并坚持使用 websockets,因为这就是整个应用程序的方式.

Also, I know i can do this via HTTP. Trying to avoid it and stick to websockets since thats how the entire app is.

非常感谢!

推荐答案

解决方案取决于文件的大小.

The solution depends on size of your file.

如果大小小于 50 MB,我会将文件的内容编码为服务器上的 base64 字符串并将此字符串发送到客户端.客户端应该接收字符串的一部分,将它们连接成单个结果并存储.收到整个字符串后,将链接(标签 )添加到您的页面,并将属性 href 设置为 "data:;base64,<;base64_encoded_file_content>". 是文件的 MIME 类型,例如text/html"或image/png".通过将 download 属性集添加到文件名来建议文件名(不适用于 OS X 上的 Chrome).

If size is less than about 50 MB, I would encode file's content to base64 string on the server and send this string to the client. Client should receive parts of the string, concat them to single result, and store. After receiving whole string, add link (tag <a>) to your page with attribute href set to "data:<data_type>;base64,<base64_encoded_file_content>". <data_type> is a mime type of your file, for example "text/html" or "image/png". Suggest file name by adding download attribute set to name of file (doesn't work for Chrome on OS X).

不幸的是,我没有大文件的解决方案.目前只有 FileEntry API 允许使用 JS 编写文件,但根据文档,它仅受 Chrome v13+ 支持,在此处了解更多信息 https://developer.mozilla.org/en-US/docs/Web/API/FileEntry.

Unfortunately I have no solution for large files. Currently there is only FileEntry API that allows to write files with JS, but according to documentation it is supported only by Chrome v13+, learn more here https://developer.mozilla.org/en-US/docs/Web/API/FileEntry.

这篇关于通过 websocket 接收文件并保存/写入本地文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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