我们的一个内部网站允许用户上传文档并将文件存储到SQL 2008数据库中。我们遇到的问题是,当您尝试打开它们时,docx总是说已损坏。单击确定后,他们然后继续打开罚款。我做错了什么? (所有其他文件类型保存正常,包括.doc)
上传代码:
// save the files
string mimeType = Request.Files[i].ContentType;
string filePath = Path.GetFileName(Request.Files[i].FileName);
string fileName = Path.GetFileName(Request.Files[i].FileName);
Stream fileStream = Request.Files[i].InputStream;
long fileLength = Request.Files[i].InputStream.Length;
if (fileLength > 0)
{
byte[] fileData = new byte[fileLength];
fileStream.Read(fileData, 0, (int)fileLength);
_fileRepo.SaveFileToDatabase(_currentUser.Username, t.EncounterId, fileName, filePath, mimeType, fileData);
}
将其插入数据库的代码
tblDocumentImage img = new tblDocumentImage();
img.DocumentImage = file; //DB field datatype = Image
...
...
_ctx.tblDocumentImage.InsertOnSubmit(img);
_ctx.SubmitChanges();
提供文件的代码
public Document DocumentById(int docID)
{
Document doc = new Document(docID;
...
var f = _ctx.tblDocumentImage.Where(di => di.DocumentID == docID).FirstOrDefault();
doc.File = (byte[])f.DocumentImage.ToArray();
return doc;
}
public ActionResult Download(int id, string filename)
{
Document doc = null;
if (id != 0)
{
doc = _fileRepo.DocumentById(id);
}
if (doc != null)
{
return File(doc.File, doc.ContentType, doc.FilenameWithExtension);
}
return File(new byte[0], "text/html");
}
答案 0 :(得分:0)
试试这样:
int fileLength = Request.Files[i].ContentLength;
而不是:
long fileLength = Request.Files[i].InputStream.Length;