Я новичок в 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
называется 'token'
типа string
к следующему методу с использованием [FromBody]
это возможно?
Обязательно:
public async Task<HttpResponseMessage> FileUpload([FromBody] string token)
{
//somecode here
}
Итак, в основном мы можем отправить multiple Content-Type
данные на веб-API? Пожалуйста, предложите. Я использую Fiddler
для тестирования webapi.
Например:
Тело запроса (JSON): { "маркер": "FV00VYAP"}
У меня также были некоторые проблемы с этим. То, что я закончил, было base64, кодирующим файл, который будет загружен в клиенте, а затем добавив его как свойство для моего PostModel. – Martin