0
我是ASP.NET Web API
的新用戶。我有一個示例FileUpload
web api(來自某個站點)將文件上傳到服務器。 以下工作正常上傳文件。如何將文件和參數一起發佈到webapi方法?
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);
}
}
但是,我想送一個parameter
稱爲string
型'token'
使用[FromBody]
是有可能下面的方法?
要求:
public async Task<HttpResponseMessage> FileUpload([FromBody] string token)
{
//somecode here
}
所以,基本上我們可以multiple Content-Type
數據發送到Web API?請建議。我正在使用Fiddler
來測試webapi。
如:
請求體(JSON): { 「令牌」: 「FV00VYAP」}
我也有這個麻煩。我最終做的是base64編碼要上傳到客戶端的文件,然後將其作爲屬性添加到我的PostModel中。 – Martin