有一个允许用户上传文件的表单。这里没什么特别的。 文件被 Controller 捕获为 HttpPostedFileBase。
然后,HttpPostedFileBase 从 Controller 发送到想要使用 HTTPClient 将该文件转发到 WEB API 的服务。
我们使用 client.PostAsync(url, content),其中内容是 MultipartFormDataContent,其中 StreamContent 是使用 IO FileRead(流)添加的。代码如下。
问题是 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# - 如何将文件作为 MultipartFormDataContent 从表单传递到 HttpClient.PostAsync,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48099674/