使用Multipart请求将文件上传到Web API [英] File upload to Web API using Multipart request
问题描述
我有一个Silverlight应用程序,该应用程序使用Web API上载作为文件流存储在数据库中的文档.目前,它是由POST完成的,其内容类型为:application/json .包含File的字节数组以及有关该文件的一些元数据的对象被序列化为JSON,并发布到Web API.然后,Web API将字节数组作为文件流保存到数据库.
I have a Silverlight application that uses Web API to upload a document that is stored in a Database as a Filestream. Currently it's done by a POST with a Content-Type: application/json. The object containing a byte array of the File along with some metadata about the file is serialized to JSON and posted to the Web API. Web API then saves the byte array as a Filestream to the Database.
以下是当前请求的示例:
Following is a sample of the current request:
<代码> { FileContent": + JVBERi0xLjUNJeLjz9MNCjEwIDAgb2JqDTw8L0xpbmVhcml6ZWQgMS9MIDI3MTg2L08gMTIvRSAyMjYyNi9OIDEvVCAyNjg4NC9IIFsgNDg5IDE2OF0 Pg1lbmRvYmoNICAgICAgICAgICAgICAgICAgDQoyNyAwIG9iag08PC9EZWNvZGVQYXJtczw8L0NvbHVtbnMgNC9QcmVkaWN0b3IgMTIg0K", 产品编号": 85c98324-092a-4D10-bab0-03912e437234", 的OrderId": 7b826322-7526-4a69-b67c-5c88a04f4c60","FileName:" test.pdf," FileType:1," FileDescription:" test}
我想将此逻辑更改为内容类型为多部分"的发布".形成我的请求的最佳方式是什么?另外,构造我的Web API控制器以处理Multipart请求的最佳方法是什么?
I would like to change this logic to Post as a Content-Type of Multipart. What would be the best way to form my request? Also, what's the best way to structure my Web API Controller to process the Multipart request?
推荐答案
这是分段上传的示例.
[HttpPost]
[Route("upload")]
public async Task<IHttpActionResult> Upload()
{
MultipartFileData file = null;
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
return UnsupportedMediaType();
}
// initialize path and provider
string root = HttpContext.Current.Server.MapPath("~/App_Data");
if (Directory.Exists(root) == false) Directory.CreateDirectory(root);
var provider = new MultipartFormDataStreamProvider(root);
// Read the form data.
await Request.Content.ReadAsMultipartAsync(provider);
try
{
// we take the first file here
file = provider.FileData[0];
// and the associated datas
int myInteger;
if (int.TryParse(provider.FormData["MyIntergerData"], out myInteger) == false)
throw new ArgumentException("myInteger is missing or not valid.");
var fileContent = File.ReadAllBytes(file.LocalFileName);
// do something with your file!
}
finally
{
// get rid of temporary file
if (file != null)
File.Delete(file.LocalFileName);
}
// successfull!
return NoContent();
}
这是我从我的API获得的示例.每次上传时,您可以有多个文件(请检查 provider.FileData
数组),以及 provider.FormData
数组中的不同数据.
This is a sample I got from an API of mine. You can have multiple files for each upload (check the provider.FileData
array), and different datas inside the provider.FormData
array.
对于此客户端方面,我建议您检查此回答此API的JS调用示例.
For the client side aspect of this I suggest you to check this answer for a sample of a JS call to this API.
希望有帮助!
这篇关于使用Multipart请求将文件上传到Web API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!