在asp.net mvc中将字节数组下载为文件

时间:2014-07-23 16:11:47

标签: c# asp.net asp.net-mvc download

我有一个字节数组,我试图下载为docx文件。我允许用户上传多个文件并创建一个新的模型对象来存储每个文件信息。然后我将编辑文件数据并返回给用户一个新文件。现在我正在尝试使用FileStreamResult从字节数组中下载文件。从我所看到和阅读的同时,似乎建议使用FileStreamResult进行研究。这是将字节数组下载为文件的最佳方法吗?为什么我收到上传方法返回时发生的错误?

我的HTML代码是:

<html>
<body>
    <div class="jumbotron">
        <h1>File Upload through HTML</h1>
        <form enctype="multipart/form-data" method="post" id="uploadForm" action="http://localhost:51906/api/FileUpload/Upload">
            <fieldset>
                <legend>Upload Form</legend>
                <ol>
                    <li>
                        <label>Upload File</label>
                        <input type="file" id="fileInput" name="fileInput" accept=".docx, .xml" multiple>
                    </li>
                    <li>
                        <input type="submit" value="Upload" id="submitBtn" class="btn">
                    </li>
                </ol>
            </fieldset>
        </form>
    </div>
</body>
</html>

我的控制器代码如下:

        [HttpPost]
        public async Task<ActionResult> Upload() //Task<FileStreamResult>
        {
            if (!Request.Content.IsMimeMultipartContent())
            {   
                throw new Exception();
                return null;
            }

            var provider = new MultipartMemoryStreamProvider();
            await Request.Content.ReadAsMultipartAsync(provider);

            List<FileUpload> fileList = new List<FileUpload>();
            foreach (var file in provider.Contents) 
            {
                FileUpload f = new FileUpload //Create a new model
                {
                    fileName = file.Headers.ContentDisposition.FileName.Trim('\"'),
                    contentType = file.Headers.ContentType.MediaType,
                    fileBuffer = await file.ReadAsByteArrayAsync()                     
                };
                fileList.Add(f);

//TEMPORARY FOR TESTING DOWNLOAD
                if (f.contentType == "application/vnd.openxmlformats-officedocument.wordprocessingml.document")
                    final = new FileUpload
                    {
                        fileName = f.fileName,
                        contentType = f.contentType,
                        fileBuffer = f.fileBuffer
                    };
            }

            //convert(fileList);           

            Stream stream = new MemoryStream(final.fileBuffer);
            FileStreamResult fsr = new FileStreamResult(stream, "application/vnd.openxmlformats-officedocument.wordprocessingml.document")
            {
                FileDownloadName = "file.docx"
            };
            return fsr;
        }

我知道在创建流和FileStreamResult对象之前一切正常。但是,当我运行代码时,我得到了这个结果:

<Error>
  <Message>An error has occurred.</Message>
  <ExceptionMessage>
         The 'ObjectContent`1' type failed to serialize the response body for content type                'application/xml; charset=utf-8'.
  </ExceptionMessage>
  <ExceptionType>
     System.InvalidOperationException
  </ExceptionType>
  <StackTrace/>
  <InnerException>
     <Message>An error has occurred.</Message>
     <ExceptionMessage>
      Type 'System.Web.Mvc.FileStreamResult' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute.  If the type is a collection, consider marking it with the CollectionDataContractAttribute.  See the Microsoft .NET Framework documentation for other supported types.
     </ExceptionMessage>
     <ExceptionType>
     System.Runtime.Serialization.InvalidDataContractException
     </ExceptionType>
     <StackTrace>   
at System.Runtime.Serialization.DataContract.DataContractCriticalHelper.ThrowInvalidDataContractException(String message, Type type)
       at System.Runtime.Serialization.DataContract.DataContractCriticalHelper.CreateDataContract(Int32 id, RuntimeTypeHandle typeHandle, Type type)
       at System.Runtime.Serialization.DataContract.DataContractCriticalHelper.GetDataContractSkipValidation(Int32 id, RuntimeTypeHandle typeHandle, Type type)
       at System.Runtime.Serialization.DataContractSerializer.GetDataContract(DataContract declaredTypeContract, Type declaredType, Type objectType)
       at System.Runtime.Serialization.DataContractSerializer.InternalWriteObjectContent(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver)
       at System.Runtime.Serialization.DataContractSerializer.InternalWriteObject(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver)
       at System.Runtime.Serialization.XmlObjectSerializer.WriteObjectHandleExceptions(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver)
       at System.Runtime.Serialization.DataContractSerializer.WriteObject(XmlWriter writer, Object graph)
       at System.Net.Http.Formatting.XmlMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content)
       at System.Net.Http.Formatting.XmlMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext)
    --- End of stack trace from previous location where exception was thrown ---
       at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
       at System.Web.Http.WebHost.HttpControllerHandler.  
       <WriteBufferedResponseContentAsync>d__14.MoveNext()
     </StackTrace>
  </InnerException>
</Error>

1 个答案:

答案 0 :(得分:0)

使用属性DataContractAttribute标记FileUpload类的fileName,contentType,fileBuffer成员