2014-07-23 1 views
1

docx 파일로 다운로드하려고하는 바이트 배열이 있습니다. 사용자가 여러 파일을 업로드하고 각 파일 정보를 저장하는 새 모델 객체를 만들도록 허용합니다. 그런 다음 파일 데이터를 편집하고 사용자에게 새 파일을 반환합니다. 지금은 FileStreamResult를 사용하여 바이트 배열에서 파일을 다운로드하려고합니다. FileStreamResult를 사용하여 연구하는 것이 권장되는 것으로 보았습니다. 바이트 배열을 파일로 다운로드하는 가장 좋은 방법입니까? 업로드 방법이 반환 될 때 발생하는 오류가 발생하는 이유는 무엇입니까?바이트 배열을 asp.net mvc 파일로 다운로드

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

답변

0

마크 파일 이름, ContentType을, 속성 DataContractAttribute와는 FileUpload 클래스의 fileBuffer 회원

+0

감사합니다. 나는 그것이 오류 메시지에서 어떻게 빠졌는지 모른다. – user3780986

관련 문제