gpt4 book ai didi

c# - 如何将文件从表单传递到 HttpClient.PostAsync 作为 MultipartFormDataContent

转载 作者:行者123 更新时间:2023-11-30 23:06:32 29 4
gpt4 key购买 nike

有一个允许用户上传文件的表单。这里没什么好看的。文件被 Controller 捕获为 HttpPostedFileBase

然后从 Controller 将 HttpPostedFileBase 发送到要使用 HTTPClient 将该文件转发到 WEB API 的服务。

我们使用 client.PostAsync(url, content),其中内容是 MultipartFormDataContent,其中 StreamContent 使用 IO FileRead (Stream) 添加。代码如下。

问题是来自 HttpPostedFileBase 的文件路径引用了用户本地计算机路径,当服务器尝试读取它时失败并显示:找不到路径“C:\Users.....”错误的一部分

尝试使用 Server.MapPath 进行播放,但在此过程中文件未保存到服务器(也许它一定是?)

Controller

[HttpPost]
public ActionResult uploadFile(HttpPostedFileBase upload, int someID)
{
FileUploadService.UploadFile(upload, someID);
return RedirectToAction("Index");
}

服务

 public static bool UploadFile(HttpPostedFileBase file, int itemID)
{
using (var content = new MultipartFormDataContent())
{
Stream fs = File.OpenRead(file.FileName); //code fails on this line
content.Add(CreateFileContent(fs, file.FileName, "text/plain"));

client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain"));
client.DefaultRequestHeaders.Add("Authorization-Token", token);

var url = String.Format(.....'code removed not important this part is working' );

var response = client.PostAsync(url, content).Result;
response.EnsureSuccessStatusCode();
if (response.IsSuccessStatusCode)
{
string responseString = response.Content.ReadAsStringAsync().Result;
return true;
}
else
{
return false;
}
}
}

private static StreamContent CreateFileContent(Stream stream, string fileName, string contentType)
{
try
{
var fileContent = new StreamContent(stream);
fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data")
{
Name = "UploadedFile",
FileName = "\"" + fileName + "\""
};
fileContent.Headers.ContentType = new MediaTypeHeaderValue(contentType);
return fileContent;
}
catch (Exception ex)
{
return null;
}
}

最佳答案

在失败的那一行,您基本上是在说从服务器上的磁盘打开一个文件,但您还没有将它保存在那里。幸运的是你不需要;您可以直接从 HttpPostedFileBase 获取流。

只需替换这个:

Stream fs = File.OpenRead(file.FileName);
content.Add(CreateFileContent(fs, file.FileName, "text/plain"));

用这个:

content.Add(CreateFileContent(file.InputStream, file.FileName, "text/plain"));

关于c# - 如何将文件从表单传递到 HttpClient.PostAsync 作为 MultipartFormDataContent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48099674/

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