【问题标题】:How to post a file along with parameter to webapi method?如何将文件与参数一起发布到 webapi 方法?
【发布时间】: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


【解决方案1】:

您可以通过查询字符串传入额外的内容,然后从您的 CustomMultipartFormDataStreamProvider 中读取。

// Read all contents of multipart message into CustomMultipartFormDataStreamProvider.
               await Request.Content.ReadAsMultipartAsync(provider);

然后您可以使用provider.FormData 来读取您传递的额外值。

// Show all the key-value pairs.
        foreach (var key in provider.FormData.AllKeys)
        {
            foreach (var val in provider.FormData.GetValues(key))
            {
                Trace.WriteLine(string.Format("{0}: {1}", key, val));
            }
        }

更多详情请见http://www.asp.net/web-api/overview/advanced/sending-html-form-data,-part-2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 2015-02-13
    • 2014-07-23
    • 2017-12-20
    • 1970-01-01
    • 2017-07-01
    • 1970-01-01
    相关资源
    最近更新 更多