我如何获得HttpInputStream的字节数组的DOCX文件? [英] How do I get a byte array from HttpInputStream for a docx file?

查看:398
本文介绍了我如何获得HttpInputStream的字节数组的DOCX文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的方法从这个职位的第一个答案:如何创建从HttpPostedFile 的字节数组,但它不适用于由于某些原因的.docx文件。

  // viewmodel.File是HttpPostedFileBase字节[] FILEDATA;
使用(VAR binaryReader =新BinaryReader(viewModel.File.InputStream))
{
    FILEDATA = binaryReader.ReadBytes(viewModel.File.ContentLength);
}

在.DOCX文件 FILEDATA 显示为 {字节[0]} ,但它与PDF文件,EXCEL文件(XLSX),pre 2007字的文件(文件),以及图像(即该值大于零)。保存到数据库中,FILEDATA是 0X

如何我从HttpInputStream的字节数组的DOCX文件?

更新结果
我的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

 字节[] = FILEDATA新的字节[viewModel.File.ContentLength]
viewModel.File.InputStream.Read(FILEDATA,0,viewModel.File.ContentLength);

但是,如果我保存的字节数组到数据库,并尝试写一个文件,这是严重损坏。保存到数据库在这种情况下,它看起来像 0x00000000000000000000000 ...

更新3 结果
这里是整个控制器的方法,虽然我不认为看到整个事情是必要的:

  [HttpPost]
    公众的ActionResult SaveChangeFile(AttachmentFormViewModel视图模型)
    {
        如果(viewModel.File == NULL)
            返回JSON(新{成功= FALSE,消息=没有找到文件,请选择一个文件,然后再试一次。},文/ X-JSON
                        JsonRequestBehavior.DenyGet);
        尝试
        {            //验证了正确的文件已被上传
            OperationResponse响应= _attachmentProcessor.ValidateAttachmentContentType(viewModel.File,(ChangeFileTypeEnum)viewModel.FileType);
            如果(!response.IsSuccess)
                返回JSON(新{成功= response.IsSuccess,消息= response.Message},文/ X-JSON,JsonRequestBehavior.DenyGet);            UpdateProjectFromCostCalculatorRequest projectValues​​ = NULL;            工作簿簿= NULL;
            文献文件= NULL;            如果(_attachmentProcessor.IsWorkbook(viewModel.File))
                工作簿=新的工作簿(viewModel.File.InputStream);            如果(_attachmentProcessor.IsDocument(viewModel.File))
                文档=新的文件(viewModel.File.InputStream);            变种文件名= Path.GetFileName(viewModel.File.FileName);            //如果成本计算,验证的值是否正确和更新有关的项目
            开关((ChangeFileTypeEnum)viewModel.FileType)
            {
                案例ChangeFileTypeEnum.CostCalculator:
                    响应= _attachmentProcessor.ValidateCostCalculator(工作簿,文件名);
                    如果(response.IsSuccess)
                        projectValues​​ = _attachmentProcessor.GetDataFromCostCalculator(练习册);                    打破;
                案例ChangeFileTypeEnum.DataValidation:
                    响应= _attachmentProcessor.ValidateDataValidation(练习册);
                    打破;
                案例ChangeFileTypeEnum.WorkPaper:
                    响应= _attachmentProcessor.ValidateWorkPaper(文件);
                    打破;
            }            //返回错误信息,如果任何验证上述失败
            如果(!response.IsSuccess)
                返回JSON(新{成功= response.IsSuccess,消息= response.Message},文/ X-JSON,JsonRequestBehavior.DenyGet);            //从流的文件并放入一个byte []保存在数据库
            字节[] FILEDATA;
            使用(VAR binaryReader =新BinaryReader(viewModel.File.InputStream))
            {
                FILEDATA = binaryReader.ReadBytes(viewModel.File.ContentLength);
            }
            var文件=新ChangeFile
                               {
                                   ChangeRequestID = viewModel.ChangeRequestId,
                                   ChangeFileTypeID = viewModel.FileType,
                                   文件= FILEDATA,
                                   文件名=文件名,
                                   的ContentType = viewModel.File.ContentType,
                                   CreatedBy = User.UserNameWithoutDomain(),
                                   UpdatedBy = User.UserNameWithoutDomain(),
                                   CreatedDate = DateTime.Now,
                                   UpdatedDate = DateTime.Now
                               };                _changeRequestService.SaveChangeFile(文件);            VAR日志=新ChangeFileImportLog {CreatedDate = DateTime.Now};
            开关((ChangeFileTypeEnum)viewModel.FileType)
            {
                案例ChangeFileTypeEnum.CostCalculator:
                    VAR项目= _changeRequestService.GetChangeProjectByPsrs(file.ChangeRequestID,projectValues​​.PsrsNumber);
                    如果(项目!= NULL)
                    {
                        _attachmentProcessor.UpdateChangeProjectWithProjectValues​​(项目,projectValues​​);
                        log.NumberOfErrors = 0;
                        log.NumberOfSegmentChanges = 0;
                        log.NumberOfWarnings = 0;
                    }
                    其他
                    {
                        log.NumberOfWarnings = 1;
                        log.Warnings =
                            的String.Format(
                                有这个变更申请与PSRS \\没有项目{0} \\。如果有,新的费用将与\\更新{1:C0} \\,
                                projectValues​​.PsrsNumber,projectValues​​.Cost);
                    }
                    打破;
                案例ChangeFileTypeEnum.DataValidation:
                    登录= _attachmentProcessor.CreateChangeSegmentsFromDataValidation(工作簿,file.ChangeRequestID,file.ChangeFileID,用户);
                    打破;
                案例ChangeFileTypeEnum.WorkPaper:
                    登录= _attachmentProcessor.UpdateChangeProjectsFromWorkPaper(文件,file.ChangeRequestID,file.ChangeFileID,
                                                                                 用户);
                    打破;
            }            log.CreatedBy = User.UserNameWithoutDomain();
            log.CreatedDate = DateTime.Now;
            log.UpdatedBy = User.UserNameWithoutDomain();
            log.UpdatedDate = DateTime.Now;            _changeRequestService.SaveChangeFileImportLog(日志,file.ChangeFileID);
            _changeRequestService.Commit();
            返回JSON(新{成功= response.IsSuccess,消息= response.Message},文/ X-JSON,JsonRequestBehavior.DenyGet);
        }
        赶上(异常前)
        {
            返回JSON(新{成功= FALSE,消息=的String.Format(遇到了系统错误:{0},前)},文/ X-JSON,JsonRequestBehavior.DenyGet);        }
    }


解决方案

原来,因为我使用的流已经(见问题的控制器的方法),它是空的,当我试图挽救它。

我不知道为什么我经历了这与DOCX,而不是因为XLSX它们都具有前保存其流消耗。我的猜测是它是与在的Aspose.Cells和Aspose.Words实现的差异。

不管,但是,我设置上清溪的位置返回到0,和它的工作。

  // viewmodel.File是HttpPostedFileBaseviewModel.File.InputStream.Position = 0; //< -----这固定它!字节[] FILEDATA;
使用(VAR binaryReader =新BinaryReader(viewModel.File.InputStream))
{
    FILEDATA = binaryReader.ReadBytes(viewModel.File.ContentLength);
}

I am using the method from the first answer in this post: How to create byte array from HttpPostedFile but it doesn't work for .docx files for some reason.

//viewmodel.File is HttpPostedFileBase

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

On .docx files fileData shows as {byte[0]}, but it works with pdfs, excel files (xlsx), pre 2007 word files (doc), and images (i.e. the value is greater than zero). Saved to the database, the fileData is 0x.

How do I get a byte array from HttpInputStream for a docx file?

UPDATE
My web.config is configured with

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

This is working with xslx files bigger than 4MB but docx files less than 80KB are not.

UPDATE 2
I can get fileData to populate using the method explained here: 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);

But if I saved that byte array to the database and try to write a file, it is severely corrupt. Saved to the database in this case it looks like 0x00000000000000000000000...

UPDATE 3
Here is the whole controller method, though I don't think seeing the whole thing is necessary:

    [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);

        }
    }

解决方案

Turns out that since I am using the stream already (see the controller method in the question), it is empty when I tried to save it.

I am not sure why I experienced this with docx and not xlsx since they both have their Streams consumed before the save. My guess is it has something to do with the differences in the Aspose.Cells and Aspose.Words implementations.

Regardless, however, I set the position on the stream back to 0, and it worked.

//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);
}

这篇关于我如何获得HttpInputStream的字节数组的DOCX文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆