C#学习教程:从多部分文件上载中读取内容到内存分享


从多部分文件上载中读取内容到内存

我在将上传的XML文件读取到字符串而不是文件时遇到问题。

我的问题是,当我尝试访问流( var stream = part.ContentReadStream )时,它就关闭了。 我觉得它正在访问封闭的文件流。 我错误地使用MultipartFormDataStreamProvider吗? 文件大小只有几千字节,所以这应该不是问题。

  [WebInvoke(Method = "POST", UriTemplate = "{importFile}")] public HttpResponseMessage Upload(string importFile, HttpRequestMessage request) { if (!request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } // Create a stream provider for setting up output streams MultipartFormDataStreamProvider streamProvider = new MultipartFormDataStreamProvider(); // Read the MIME multipart content using the stream provider we just created. var task = request.Content.ReadAsMultipartAsync(streamProvider); task.Wait(); IEnumerable bodyparts = task.Result; string submitter; if (!bodyparts.TryGetFormFieldValue("submitter", out submitter)) { submitter = "unknown"; } // Get list of local file names from stream provider IDictionary bodyPartFileNames = streamProvider.BodyPartFileNames; var parser = this.parserFactoryFactory.CreateParser(); foreach (var part in bodyparts) { using (var stream = part.ContentReadStream) { using (var streamReader = new StreamReader(stream)) { string content = streamReader.ReadToEnd(); var results = parser.Parse(content); } } } return new HttpResponseMessage(HttpStatusCode.Accepted); } 

这是我的post

 

Data import test

解决方案实际上非常简单。 当我们不处理文件时,不需要MultipartFormDataStreamProvider。 这对我的案子来说非常顺利。

上述就是C#学习教程:从多部分文件上载中读取内容到内存分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—猴子技术宅(www.ssfiction.com)

 [WebInvoke(Method = "POST", UriTemplate = "{importFile}")] public HttpResponseMessage Upload( string importFile, HttpRequestMessage request) { if (!request.Content.IsMimeMultipartContent()) throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); // Read the MIME multipart content var task = request.Content.ReadAsMultipartAsync(); task.Wait(); IEnumerable bodyparts = task.Result; string submitter; if (!bodyparts.TryGetFormFieldValue("submitter", out submitter)) submitter = "unknown"; var parser = this.parserFactoryFactory.CreateParser(); foreach (var part in bodyparts) { using (var stream = part.ContentReadStream) { using (var streamReader = new StreamReader(stream)) { string content = streamReader.ReadToEnd(); var results = parser.Parse(content); if (results.IsValid) // do something } } } var message = new HttpResponseMessage(HttpStatusCode.Accepted); return message; } 

本文来自网络收集,不代表猴子技术宅立场,如涉及侵权请点击右边联系管理员删除。

如若转载,请注明出处:https://www.ssfiction.com/ckf/960090.html

发表评论

邮箱地址不会被公开。 必填项已用*标注