【发布时间】:2015-10-01 06:13:29
【问题描述】:
我是ASP.NET Web API 的新手。我有一个示例FileUpload web api(来自某个站点)将文件上传到服务器。
以下适用于上传文件。
public async Task<HttpResponseMessage> FileUpload()
{
// Check whether the POST operation is MultiPart?
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
// Prepare CustomMultipartFormDataStreamProvider in which our multipart form
// data will be loaded.
//string fileSaveLocation = HttpContext.Current.Server.MapPath("~/App_Data");
string fileSaveLocation = HttpContext.Current.Server.MapPath("~/UploadedFiles");
CustomMultipartFormDataStreamProvider provider = new CustomMultipartFormDataStreamProvider(fileSaveLocation);
List<string> files = new List<string>();
try
{
// Read all contents of multipart message into CustomMultipartFormDataStreamProvider.
await Request.Content.ReadAsMultipartAsync(provider);
foreach (MultipartFileData file in provider.FileData)
{
files.Add(Path.GetFileName(file.LocalFileName));
}
// Send OK Response along with saved file names to the client.
return Request.CreateResponse(HttpStatusCode.OK, files);
}
catch (System.Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
// We implement MultipartFormDataStreamProvider to override the filename of File which
// will be stored on server, or else the default name will be of the format like Body-
// Part_{GUID}. In the following implementation we simply get the FileName from
// ContentDisposition Header of the Request Body.
public class CustomMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
{
public CustomMultipartFormDataStreamProvider(string path) : base(path) { }
public override string GetLocalFileName(HttpContentHeaders headers)
{
return headers.ContentDisposition.FileName.Replace("\"", string.Empty);
}
}
但是,我想使用[FromBody] 将类型为string 的'token' 称为'token' 发送到以下方法,这可能吗?
必填:
public async Task<HttpResponseMessage> FileUpload([FromBody] string token)
{
//somecode here
}
那么,基本上我们可以将multiple Content-Type 数据发送到web api 吗?请建议。我正在使用Fiddler 来测试 webapi。
例如:
请求正文(json): {“令牌”:“FV00VYAP”}
【问题讨论】:
-
我也遇到了一些麻烦。我最终做的是对要上传到客户端的文件进行 base64 编码,然后将其作为属性添加到我的 PostModel。
标签: asp.net-web-api content-type fiddler