One of our internal websites allows for users to upload documents and stores the files into the SQL 2008 database. The problem we are encountering is that docx are always saying the are corrupted when you try and open them. After you click OK, they then proceed to open fine. What I am doing wrong? (All other file types save fine, including .doc)
Upload code:
// 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);
}
Code that inserts it into the database
tblDocumentImage img = new tblDocumentImage();
img.DocumentImage = file; //DB field datatype = Image
...
...
_ctx.tblDocumentImage.InsertOnSubmit(img);
_ctx.SubmitChanges();
Code that serves the file back out
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");
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…