【发布时间】:2017-06-04 05:16:32
【问题描述】:
我有一个项目,我将文档作为 blob 存储在 MySQL 数据库中,然后使用 C# 将它们作为字节数组下载:
public static byte[] GetFile(string fileName)
{
conn.Open();
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandText = ...
using (MySqlDataReader reader = cmd.ExecuteReader())
{
reader.Read();
if (reader.HasRows)
{
return Util.ObjectToByteArray(reader["Content"]);
}
...
}
...
public static byte[] ObjectToByteArray(object obj)
{
BinaryFormatter bf = new BinaryFormatter();
using (var ms = new MemoryStream())
{
bf.Serialize(ms, obj);
return ms.ToArray();
}
}
我像这样上传文件:
byte[] newFile = File.ReadAllBytes(fileName);
然后像这样下载:
File.WriteAllBytes(path + "\\" + selectedFileName,
DocumentTable.GetFile(selectedFileName));
但是当我下载文件时,它们已损坏并且无法打开(例如 Excel 文件,可以打开一些其他类型的文件)。下载文件的扩展名似乎是正确的,但我收到“文件扩展名或文件格式无效”的消息。
【问题讨论】:
-
不要将文件保存在数据库中。 stackoverflow.com/a/41235395/267540
-
获取一个差异工具,然后在对称阶段工作 - 做涉及某种转换的项目的最小部分,然后运行应该撤消该转换的位,然后将输出与输入。然后构建并增加复杂性(上传/下载、与数据库交互等)
标签: c# mysql blob file-format