【问题标题】:how to post httppostedfile to webapi如何将 httppostedfile 发布到 webapi
【发布时间】:2015-06-03 10:40:32
【问题描述】:
如何将 httppostedfile 发布到 webapi?
基本上,我希望用户选择一个 excel 文件,然后将其发布到我的 webapi。
gui 是用经典的 asp.net 制作的,webapi 是用新的 .NET apicontroller 制作的。
我之前做过一些 api 编码,但后来我使用了 JSON,这似乎不适用于这种对象。
请有人指出正确的方向,以便我可以继续搜索信息。现在我什至不知道要搜索什么。
【问题讨论】:
标签:
c#
asp.net
asp.net-mvc-4
asp.net-web-api
【解决方案1】:
我通过这样做解决了这个问题:
在我的控制器中:
using (var client = new HttpClient())
using (var content = new MultipartFormDataContent())
{
client.BaseAddress = new Uri(System.Configuration.ConfigurationManager.AppSettings["PAM_WebApi"]);
var fileContent = new ByteArrayContent(excelBytes);
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = fileName
};
content.Add(fileContent);
var result = client.PostAsync("api/Product", content).Result;
}
这是我的 ApiController:
[RoutePrefix("api/Product")]
public class ProductController : ApiController
{
public async Task<List<string>> PostAsync()
{
if (Request.Content.IsMimeMultipartContent())
{
string uploadPath = HttpContext.Current.Server.MapPath("~/uploads");
if (!System.IO.Directory.Exists(uploadPath))
{
System.IO.Directory.CreateDirectory(uploadPath);
}
MyStreamProvider streamProvider = new MyStreamProvider(uploadPath);
await Request.Content.ReadAsMultipartAsync(streamProvider);
List<string> messages = new List<string>();
foreach (var file in streamProvider.FileData)
{
FileInfo fi = new FileInfo(file.LocalFileName);
messages.Add("File uploaded as " + fi.FullName + " (" + fi.Length + " bytes)");
}
return messages;
}
else
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.BadRequest, "Invalid Request!");
throw new HttpResponseException(response);
}
}
}
public class MyStreamProvider : MultipartFormDataStreamProvider
{
public MyStreamProvider(string uploadPath)
: base(uploadPath)
{
}
public override string GetLocalFileName(HttpContentHeaders headers)
{
string fileName = headers.ContentDisposition.FileName;
if (string.IsNullOrWhiteSpace(fileName))
{
fileName = Guid.NewGuid().ToString() + ".xls";
}
return fileName.Replace("\"", string.Empty);
}
}
我在教程中找到了这段代码,所以我不是值得称赞的人。
所以在这里我将文件写入一个文件夹。由于 mysreamprovider,我可以获得与我第一次添加到 GUI 中的文件相同的文件名。我还将结尾“.xls”添加到文件中,因为我的程序只会处理 excel 文件。因此,我在 GUI 的输入中添加了一些验证,以便我知道添加的文件是一个 excel 文件。