2013-10-07 99 views
9

我在這篇文章中使用了第一個答案中的方法:How to create byte array from HttpPostedFile,但由於某些原因它不適用於.docx文件。如何從HttpInputStream獲取一個docx文件的字節數組?

//viewmodel.File is HttpPostedFileBase 

byte[] fileData; 
using (var binaryReader = new BinaryReader(viewModel.File.InputStream)) 
{ 
    fileData = binaryReader.ReadBytes(viewModel.File.ContentLength); 
} 

上的.docx文件fileData顯示爲{byte[0]},但它與PDF的工作,Excel文件(XLSX),前2007字的文件(DOC)和圖像(即值大於零)。保存到數據庫中,fileData是0x

如何從HttpInputStream獲取一個docx文件的字節數組?

UPDATE
我的web.config配置了

<httpRuntime targetFramework="4.5" maxRequestLength="102400" /> 

這與XSLX文件超過4MB大,但docx文件小於80KB的工作都沒有。

更新2
我能得到FILEDATA使用方法這裏解釋來填充:http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.fileupload.postedfile.aspx

byte[] fileData = new byte[viewModel.File.ContentLength]; 
viewModel.File.InputStream.Read(fileData, 0, viewModel.File.ContentLength); 

但是,如果我保存的字節數組到數據庫,並嘗試寫一個文件,這是嚴重腐敗。保存到數據庫在這種情況下,它看起來像0x00000000000000000000000...

更新3
這裏是整個控制器的方法,但我不認爲看到整個事情是必要的:

[HttpPost] 
    public ActionResult SaveChangeFile(AttachmentFormViewModel viewModel) 
    { 
     if (viewModel.File == null) 
      return Json(new { success = false, message = "No file was found, please select a file and try again." }, "text/x-json", 
         JsonRequestBehavior.DenyGet); 
     try 
     { 

      //Validate that the right kind of File has been uploaded 
      OperationResponse response = _attachmentProcessor.ValidateAttachmentContentType(viewModel.File, (ChangeFileTypeEnum)viewModel.FileType); 
      if (!response.IsSuccess) 
       return Json(new { success = response.IsSuccess, message = response.Message }, "text/x-json", JsonRequestBehavior.DenyGet); 

      UpdateProjectFromCostCalculatorRequest projectValues = null; 

      Workbook workbook = null; 
      Document document = null; 

      if (_attachmentProcessor.IsWorkbook(viewModel.File)) 
       workbook = new Workbook(viewModel.File.InputStream); 

      if (_attachmentProcessor.IsDocument(viewModel.File)) 
       document = new Document(viewModel.File.InputStream); 

      var filename = Path.GetFileName(viewModel.File.FileName); 

      //if cost calc, validate that the values are correct and update related project 
      switch ((ChangeFileTypeEnum)viewModel.FileType) 
      { 
       case ChangeFileTypeEnum.CostCalculator: 
        response = _attachmentProcessor.ValidateCostCalculator(workbook, filename); 
        if (response.IsSuccess) 
         projectValues = _attachmentProcessor.GetDataFromCostCalculator(workbook); 

        break; 
       case ChangeFileTypeEnum.DataValidation: 
        response = _attachmentProcessor.ValidateDataValidation(workbook); 
        break; 
       case ChangeFileTypeEnum.WorkPaper: 
        response = _attachmentProcessor.ValidateWorkPaper(document); 
        break; 
      } 

      //return error message if any of the validations above failed 
      if (!response.IsSuccess) 
       return Json(new { success = response.IsSuccess, message = response.Message }, "text/x-json", JsonRequestBehavior.DenyGet); 

      //get the file from the stream and put into a byte[] for saving the database 
      byte[] fileData; 
      using (var binaryReader = new BinaryReader(viewModel.File.InputStream)) 
      { 
       fileData = binaryReader.ReadBytes(viewModel.File.ContentLength); 
      } 
      var file = new ChangeFile 
           { 
            ChangeRequestID = viewModel.ChangeRequestId, 
            ChangeFileTypeID = viewModel.FileType, 
            File = fileData, 
            Filename = filename, 
            ContentType = viewModel.File.ContentType, 
            CreatedBy = User.UserNameWithoutDomain(), 
            UpdatedBy = User.UserNameWithoutDomain(), 
            CreatedDate = DateTime.Now, 
            UpdatedDate = DateTime.Now 
           }; 

       _changeRequestService.SaveChangeFile(file); 

      var log = new ChangeFileImportLog { CreatedDate = DateTime.Now }; 
      switch ((ChangeFileTypeEnum)viewModel.FileType) 
      { 
       case ChangeFileTypeEnum.CostCalculator: 
        var project = _changeRequestService.GetChangeProjectByPsrs(file.ChangeRequestID, projectValues.PsrsNumber); 
        if (project != null) 
        { 
         _attachmentProcessor.UpdateChangeProjectWithProjectValues(project, projectValues); 
         log.NumberOfErrors = 0; 
         log.NumberOfSegmentChanges = 0; 
         log.NumberOfWarnings = 0; 
        } 
        else 
        { 
         log.NumberOfWarnings = 1; 
         log.Warnings = 
          String.Format(
           "There is no project on this Change Request with PSRS \"{0}\". If there was, the new cost would be updated with \"{1:C0}\"", 
           projectValues.PsrsNumber, projectValues.Cost); 
        } 
        break; 
       case ChangeFileTypeEnum.DataValidation: 
        log = _attachmentProcessor.CreateChangeSegmentsFromDataValidation(workbook, file.ChangeRequestID, file.ChangeFileID, User); 
        break; 
       case ChangeFileTypeEnum.WorkPaper: 
        log = _attachmentProcessor.UpdateChangeProjectsFromWorkPaper(document, file.ChangeRequestID, file.ChangeFileID, 
                       User); 
        break; 
      } 

      log.CreatedBy = User.UserNameWithoutDomain(); 
      log.CreatedDate = DateTime.Now; 
      log.UpdatedBy = User.UserNameWithoutDomain(); 
      log.UpdatedDate = DateTime.Now; 

      _changeRequestService.SaveChangeFileImportLog(log, file.ChangeFileID); 
      _changeRequestService.Commit(); 
      return Json(new { success = response.IsSuccess, message = response.Message }, "text/x-json", JsonRequestBehavior.DenyGet); 
     } 
     catch (Exception ex) 
     { 
      return Json(new { success = false, message = String.Format("A system error was encountered: {0}", ex) }, "text/x-json", JsonRequestBehavior.DenyGet); 

     } 
    } 
+1

一個docx文件不應該被視爲任何不同於任何其他文件類型。 –

+0

沒有理由發生這種情況。你是什​​麼意思「空白」? filedata null?並沒有拋出異常? – Vivek

+0

如果其他文件正在運行,文件可能大於允許的上載大小。看到這篇文章,http://stackoverflow.com/questions/288612/how-to-increase-the-max-upload-file-size-in-asp-net,配置文件大小。 –

回答

9

原來因爲我已經在使用流(請參閱問題中的控制器方法),所以當我試圖保存它時它是空的。

我不知道爲什麼我用docx而不用xlsx,因爲它們都在保存前消耗了它們的Streams。我的猜測是它與Aspose.Cells和Aspose.Words實現中的差異有關。

但是,無論如何,我將流中的位置設置回0,並且工作正常。

//viewmodel.File is HttpPostedFileBase 

viewModel.File.InputStream.Position = 0; //<-----This fixed it! 

byte[] fileData; 
using (var binaryReader = new BinaryReader(viewModel.File.InputStream)) 
{ 
    fileData = binaryReader.ReadBytes(viewModel.File.ContentLength); 
} 
相關問題