title: Downloading a byte array as a file in asp.net mvc
body: <p>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?</p>
  
  <p>My html code is:</p>
  
  <pre><code>&lt;html&gt;
  &lt;body&gt;
      &lt;div class="jumbotron"&gt;
          &lt;h1&gt;File Upload through HTML&lt;/h1&gt;
          &lt;form enctype="multipart/form-data" method="post" id="uploadForm" action="http://localhost:51906/api/FileUpload/Upload"&gt;
              &lt;fieldset&gt;
                  &lt;legend&gt;Upload Form&lt;/legend&gt;
                  &lt;ol&gt;
                      &lt;li&gt;
                          &lt;label&gt;Upload File&lt;/label&gt;
                          &lt;input type="file" id="fileInput" name="fileInput" accept=".docx, .xml" multiple&gt;
                      &lt;/li&gt;
                      &lt;li&gt;
                          &lt;input type="submit" value="Upload" id="submitBtn" class="btn"&gt;
                      &lt;/li&gt;
                  &lt;/ol&gt;
              &lt;/fieldset&gt;
          &lt;/form&gt;
      &lt;/div&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>My controller code is as follows:</p>
  
  <pre><code>        [HttpPost]
          public async Task&lt;ActionResult&gt; Upload() //Task&lt;FileStreamResult&gt;
          {
              if (!Request.Content.IsMimeMultipartContent())
              {   
                  throw new Exception();
                  return null;
              }
  
              var provider = new MultipartMemoryStreamProvider();
              await Request.Content.ReadAsMultipartAsync(provider);
  
              List&lt;FileUpload&gt; fileList = new List&lt;FileUpload&gt;();
              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;
          }
  </code></pre>
  
  <p>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:</p>
  
  <pre><code>&lt;Error&gt;
    &lt;Message&gt;An error has occurred.&lt;/Message&gt;
    &lt;ExceptionMessage&gt;
           The 'ObjectContent`1' type failed to serialize the response body for content type                'application/xml; charset=utf-8'.
    &lt;/ExceptionMessage&gt;
    &lt;ExceptionType&gt;
       System.InvalidOperationException
    &lt;/ExceptionType&gt;
    &lt;StackTrace/&gt;
    &lt;InnerException&gt;
       &lt;Message&gt;An error has occurred.&lt;/Message&gt;
       &lt;ExceptionMessage&gt;
        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.
       &lt;/ExceptionMessage&gt;
       &lt;ExceptionType&gt;
       System.Runtime.Serialization.InvalidDataContractException
       &lt;/ExceptionType&gt;
       &lt;StackTrace&gt;   
  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.  
         &lt;WriteBufferedResponseContentAsync&gt;d__14.MoveNext()
       &lt;/StackTrace&gt;
    &lt;/InnerException&gt;
  &lt;/Error&gt;
  </code></pre>