如何从 HttpInputStream 获取 docx 文件的字节数组?

2024-04-18

我正在使用这篇文章第一个答案中的方法:如何从 HttpPostedFile 创建字节数组 https://stackoverflow.com/questions/359894/how-to-create-byte-array-from-httppostedfile但由于某种原因,它不适用于 .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 年之前的 word 文件 (doc) 和图像(即值大于零)。保存到数据库中,fileData为0x.

如何从 HttpInputStream 获取 docx 文件的字节数组?

UPDATE
我的 web.config 配置为

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

这适用于大于 4MB 的 xlsx 文件,但不适用于小于 80KB 的 docx 文件。

UPDATE 2
我可以使用此处解释的方法来填充 fileData:http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.fileupload.postedfile.aspx 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...

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

        }
    }

事实证明,由于我已经在使用流(请参阅问题中的控制器方法),因此当我尝试保存它时它是空的。

我不知道为什么我在使用 docx 而不是 xlsx 时遇到了这种情况,因为它们都在保存之前消耗了流。我的猜测是这与 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);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何从 HttpInputStream 获取 docx 文件的字节数组? 的相关文章

随机推荐

  • IntelliJ IDEA - Eclipse .classpath 文件和相对位置?

    我想将 IntelliJ IDEA 与 Eclipse 项目一起使用 而不转换项目格式 我现在遇到的主要问题是在我的 classpath 文件中 我们有如下条目
  • Eclipse 中缺少“注释处理”菜单

    我用这个手册https github com excilys androidannotations wiki Eclipse Only Configuration https github com excilys androidannota
  • 如何将 IN 子句与 mysqli 准备好的语句一起使用[重复]

    这个问题在这里已经有答案了 我正在使用准备好的语句将一些旧代码移至新的 msqli 接口 但我在使用包含 IN 子句的 SQL 语句时遇到了问题 我通常会这样做 ids 123 535 345 567 878 sql SELECT FROM
  • “父框基线”的定义是什么?

    我无法理解以下摘录10 可视化格式化模型详细信息 W3C https www w3 org TR CSS2 visudet html 摘录 基线 将框的基线与父框的基线对齐 如果该框没有基线 请将下边距边缘与父级的基线对齐 在这种情况下 父
  • 具有 Flux 模式的中继缓存?

    我真的很想将 Relay 缓存合并到我的 Flux 存储中 这样我就可以进行 时间旅行 并深入了解应用程序 看起来中继存储和操作都是不可序列化的类 这很糟糕 但看起来我应该能够将缓存与网络请求分开并将缓存保存在 Flux 存储中 这听起来有
  • Vista/Win7 Delphi 音频设备信息

    有没有办法在 Vista 或 Win 7 上使用 delphi D2009 获取所有音频设备名称 我设法获取设备数量 并使用 IMMDevice 获取设备 PropertyStore 但我无法继续 多谢 ask the PropertySt
  • 如何在Dockerfile中下载并解压

    所以 我有 它有效 但我想改变立即下载文件并解压它的方式 Dockerfile FROM wordpress fpm Copying themes from local COPY wordpress var www html wp cont
  • Newtonsoft.Json 可在 Unity 编辑器中运行,但无法在移动设备上运行

    我正在 Unity 中编写一个按类别提问和回答的游戏 类别是通过返回 JSON 文本的 PHP 脚本获取的 当我在 UnityEditor 中使用此解决方案时 它可以正常工作 但是当我在移动设备上安装 apk 时 反序列化不起作用 与 my
  • 带圆角的方形进度条

    我正在尝试在 dart flutter 中构建一种圆形方形进度条 也许有人知道如何使其成为可能 我已经尝试了所有 油漆 边框等等 但没有成功 示例图像 圆形方形进度条 https i stack imgur com jhy9Q png 你可
  • 在 Python 中为现有 PDF 创建大纲/目录

    我正在使用 pyPdf 将多个 PDF 文件合并为一个 这很好用 但我还需要向生成的 PDF 文件添加目录 大纲 书签 pyPdf 似乎只支持读取大纲 Reportlab 允许我创建它们 但开源版本不支持加载 PDF 文件 因此无法向现有文
  • 一个本地 .resx 字符串可以引用另一个本地 .resx 字符串吗?

    我正在尝试确定是否可以将串联字符串添加到我的本地 resx 文件之一 这个例子应该澄清 假设我有一个简单的 ASP NET 网页 由 1 一个标签 其文本是重要关键字 2 一个带有必填字段验证的输入和 3 一个导致验证发生的按钮组成 lbl
  • JodaTime中如何获取本机的时区?

    如何检测本地计算机所在的时区 I tried DateTimeZone getDefault 但如果机器位于德国 那么这不会给我例如时区 德国 有可能吗 DateTimeZone getDefault 如果您的主机位于德国 将返回您的时区
  • 没有 jpa 的 Spring 和 Hibernate

    对于我的新项目 我计划使用 Hibernate 5 和 Spring 4 并且一如既往地喜欢分成不同的层 项目 梯度依赖 org springframework spring webmvc 4 2 1 RELEASE org springf
  • 获取.NET程序集的日期[重复]

    这个问题在这里已经有答案了 如何从当前 NET 程序集中检索创建日期 我想添加一些非常简单的功能 让我的应用程序在主程序集构建日期一周后停止工作 我已经编写了在给定日期后杀死我的应用程序的代码 我只需要以编程方式从程序集中检索创建日期 以下
  • 分析 mex 函数

    我刚刚用 c 将 Matlab 程序重写为 mex 函数以加快速度 并取得了出色的结果 这个优化决策是一个非常非常好的主意 无需线程即可将速度提高 20 倍 它仍然让我很好奇 mex 函数将时间花在什么上 并希望找出可能的瓶颈 我正在寻找一
  • 创建自定义表格表示的函数

    我使用下面的代码来概述我的部分数据 从以下代码中创建函数的最佳方法是什么 它将采用 dataList 以及一些图形选项 例如颜色 作为参数 并返回自定义的表格表示形式 如下所示 overviewtheData Text Grid Map R
  • Symfony 2 FOS 用户捆绑包 Bootstrap 模式 AJAX 登录

    有没有人已经使用 Symfony 2 和 FOS User Bundle 在 Bootstrap 模式中构建了登录表单 这是我现在所拥有的 src Webibli UserBundle Resources config service ym
  • 使用 PHP 生成 Windows .lnk 文件

    我正在开发一个项目 其中涉及运行 ProFTPd 的 FTP 服务器和为用户创建帐户的 PHP MySQL 后端 创建帐户后 系统会向用户发送电子邮件 其中包含其帐户详细信息以及下载 FileZilla 或 Cyber Duck 的说明 具
  • Publish 不是改造 web.config 吗?

    我制造了一个web config 完整文件 http pastebin com rYreaVyP 它不显示 XML 错误
  • 如何从 HttpInputStream 获取 docx 文件的字节数组?

    我正在使用这篇文章第一个答案中的方法 如何从 HttpPostedFile 创建字节数组 https stackoverflow com questions 359894 how to create byte array from http