gpt4 book ai didi

c# - 如何解析 MultipartFormDataContent

转载 作者:行者123 更新时间:2023-12-04 11:34:30 33 4
gpt4 key购买 nike

我正在编写一个 Web API 服务,我想在其中接受一个文件(图像)和一个包含有关图像的关键信息的序列化对象 (JSON)。图像部分没有问题,但是当我添加包含反序列化对象的字符串内容时,我在尝试确定哪个是哪个并采取相应措施时遇到问题。

客户端代码如下所示:

HttpClient client = new HttpClient();

MultipartFormDataContent content = new MultipartFormDataContent();
content.Add(new StreamContent(File.Open("c:\\MyImages\\Image00.jpg", FileMode.Open)), "image_file", "Image00.jpg");

ImageKeys ik = new ImageKeys { ImageId = "12345", Timestamp = DateTime.Now.ToString() };
JavaScriptSerializer js = new JavaScriptSerializer();
if (ik != null)
{
content.Add(new StringContent(js.Serialize(ik), Encoding.UTF8, "application/json"), "image_keys");
}

string uri = "http://localhost/MyAPI/api/MyQuery/TransferFile";
var request = new HttpRequestMessage()
{
RequestUri = new Uri(uri),
Method = HttpMethod.Post
};

request.Content = content;

string responseStr = "";
try
{
HttpResponseMessage result = client.SendAsync(request).Result;
string resultContent = string.Format("{0}:{1}", result.StatusCode, result.ReasonPhrase);

//
// Handle the response
//
responseStr = resultContent;
}
catch (Exception ex)
{
responseStr = ex.Message;
}

listBox1.Items.Add(responseStr);

所以我首先包含图像文件,然后包含一个作为 StringContent 的序列化对象。在服务器端,我使用以下代码来解析消息。
HttpRequestMessage request = this.Request;
HttpResponseMessage ret = new HttpResponseMessage();

//
// Verify that this is an HTML Form file upload request
//
if (!request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}

string root = "c:\\tmp\\uploads";
if (!Directory.Exists(root))
{
Directory.CreateDirectory(root);
}

//
// Create a stream provider for setting up output streams that saves the output under c:\tmp\uploads
// If you want full control over how the stream is saved then derive from MultipartFormDataStreamProvider
// and override what you need.
//
MultipartFormDataStreamProvider streamProvider = new MultipartFormDataStreamProvider(root);

try
{
await request.Content.ReadAsMultipartAsync(streamProvider);
foreach (var file in streamProvider.Contents)
{
if (file.Headers.ContentDisposition.Name == "image_file")
{
FileInfo finfo = new FileInfo(streamProvider.FileData.First().LocalFileName);

string destFile = Path.Combine(root, streamProvider.FileData.First().Headers.ContentDisposition.FileName.Replace("\"", ""));
//
// File.Move cannot deal with duplicate files
// Ensure that the target does not exist.
//
if (File.Exists(destFile))
{
File.Delete(destFile);
}

File.Move(finfo.FullName, destFile);
}
else if (file.Headers.ContentDisposition.Name == "image_keys")
{
// deserialize key class
string str = file.ReadAsStringAsync().Result;

JavaScriptSerializer js = new JavaScriptSerializer();
ImageKeys ik = js.Deserialize<ImageKeys>(str);
}
}

ret.StatusCode = HttpStatusCode.OK;
ret.Content = new StringContent("File uploaded.");
}
catch (Exception ex)
{
ret.StatusCode = HttpStatusCode.UnsupportedMediaType;
ret.Content = new StringContent("File upload failed.");
}

return ret;

foreach 循环尝试将多部分内容中的每个项目作为文件处理,但我想分别处理各种内容类型,但我不清楚它们是如何描述的。
谢谢

最佳答案

您可以将 Content 转换为 MultipartFormDataContent 并对其进行迭代。根据内容类型,您可以将其作为文件或字符串读取。字符串内容类型示例:

var dataContents = request.Content as MultipartFormDataContent;

foreach (var dataContent in dataContents)
{
var name = dataContent.Headers.ContentDisposition.Name;
var value = dataContent.ReadAsStringAsync().Result;
...
}

关于c# - 如何解析 MultipartFormDataContent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30783360/

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