Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

c# - Uploaded Docx Files are getting corrupted

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try like this:

int fileLength = Request.Files[i].ContentLength;

instead of:

long fileLength = Request.Files[i].InputStream.Length;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...