Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在asp.net mvc中将字节数组下载为文件_C#_Asp.net_Asp.net Mvc_Download - Fatal编程技术网

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

C# 在asp.net mvc中将字节数组下载为文件,c#,asp.net,asp.net-mvc,download,C#,Asp.net,Asp.net Mvc,Download,我有一个字节数组,我正试图下载为docx文件。我允许用户上传多个文件,并创建一个新的模型对象来存储每个文件信息。然后我将编辑文件数据并向用户返回一个新文件。现在我正试图用FileStreamResult从字节数组下载一个文件。从我在使用FileStreamResult进行研究时所看到和阅读的内容来看,似乎推荐使用FileStreamResult。这是将字节数组作为文件下载的最佳方式吗?为什么我的上传方法返回时会出现错误 我的html代码是: <html> <body>

我有一个字节数组,我正试图下载为docx文件。我允许用户上传多个文件,并创建一个新的模型对象来存储每个文件信息。然后我将编辑文件数据并向用户返回一个新文件。现在我正试图用FileStreamResult从字节数组下载一个文件。从我在使用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>

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

谢谢。我不知道我怎么会在错误信息中漏掉这个。