gpt4 book ai didi

c# - 从多部分文件上传中读取内容到内存

转载 作者:行者123 更新时间:2023-11-30 22:33:36 29 4
gpt4 key购买 nike

我在将上传的 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<HttpContent> bodyparts = task.Result;
string submitter;
if (!bodyparts.TryGetFormFieldValue("submitter", out submitter))
{
submitter = "unknown";
}

// Get list of local file names from stream provider
IDictionary<string, string> 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);
}

这是我的帖子

<h3>Data import test</h3>

<form action="/api/data/Upload" enctype="multipart/form-data" method="POST">
<input type="file" name="importFile"/>
<input type="submit" value="Upload"/>
</form>

最佳答案

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

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

关于c# - 从多部分文件上传中读取内容到内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8239307/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com