简体   繁体   中英

Downloading a byte array as a file in asp.net mvc

I have a byte array that I am trying to download as a docx file. I allow the user to upload multiple files and create a new model object to store each of the files information. Then I will edit the files data and return to the user a new file. Right now I am trying to download a file from a byte array with FileStreamResult. From what I have seen and read while researching using FileStreamResult seems to be recommended. Is this the best way to download the byte array as a file? Why am I getting the error that is occurring when my upload method returns?

My html code is:

<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>

My controller code is as follows:

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

I know that everything up until where I create the stream and the FileStreamResult object is working. However when I run the code I get this as a result:

<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>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM