【发布时间】:2016-10-26 17:14:19
【问题描述】:
我有 zip 文件,我想对其进行编码并将其作为字符串发送并解码并将其保存在服务器端:
这是客户端(JS)中的编码代码:
var fileAsText = ''
var reader = new FileReader()
reader.onload = function (event) {
fileAsText = encodeURIComponent(event.target.result)
}
reader.readAsText(zipFile)
zipFile 是输入文件对象(由用户上传)。
我在JSON 中以Post 发送的fileAsText 字符串(这就是我使用encodeURIComponent 的原因)
一切正常,但在服务器端,我想将此字符串 解码回 为二进制(zip 文件)并提取它。我想得到完全相同的文件用户在客户端上传。
这是我在 c# 中的代码:
using (var bw = new BinaryWriter(File.Open("fileTest.zip", FileMode.Create)))
{
bw.Write(HttpUtility.UrlDecode(fileAsText));
}
问题:我没有得到相同的文件(二进制数据不同)
我相信解码器HttpUtility.UrlDecode不适合encodeURIComponent
知道如何获取用户上传的相同文件二进制数据吗?
【问题讨论】:
-
您可能不应该将其作为文本阅读...只需按原样发送 blob...然后使用 formData 将 json 和文件结合起来。从您使用文件阅读器将其作为文本读取的那一刻起,您就获得了损坏的数据。 Javascript 不能很好地处理二进制字符串
-
@Endless 我知道,我将其作为文本阅读是有原因的,解释起来很复杂(这是限制)如果我必须使用 reader.readAsText,请找到解决方案谢谢
-
为什么要发布为json?这是个坏主意。如果您需要更多字段,您可以发送
xhr.send(zipFile)或使用分段上传 (FormData) -
我使用 Json RPC 作为通信 github.com/Astn/JSON-RPC.NET 所以我只能将 Json 发送到服务器。我无法将文件发送到服务器
-
那么我建议您阅读
asDataURL(base64) 但这会给您带来开销和大约 3 倍的带宽
标签: javascript c# encoding zip decoding