Dan*_*son 5 c# asp.net asp.net-mvc-4 asp.net-web-api
如何将httppostedfile发布到webapi?基本上我希望用户选择一个excel文件,我想将它发布到我的webapi.
gui是用经典的asp.net制作的,webapi是用新的.NET apicontroller制作的.
我之前做过一些api编码,但后来我使用了JSON,这似乎对这种对象效果不佳.
有人可以请指出我正确的方向,以便我可以继续搜索信息.现在我甚至不知道要搜索什么.
我通过这样做解决了这个问题:在我的控制器中:
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;
}
Run Code Online (Sandbox Code Playgroud)
这是我的 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);
}
}
Run Code Online (Sandbox Code Playgroud)
我在教程中找到了这段代码,所以我不是被认可的人。所以这里我将文件写入一个文件夹。由于 mysreamprovider,我可以获得与我第一次在 GUI 中添加的文件相同的文件名。我还将结尾的“.xls”添加到文件中,因为我的程序仅处理 Excel 文件。因此,我在 GUI 中的输入中添加了一些验证,以便我知道添加的文件是 Excel 文件。
归档时间: |
|
查看次数: |
2510 次 |
最近记录: |