Upload files via POST in ASP.NET Web API
File uploading in ASP.NET Web API requires a customized approach. In order to receive and process POST images or files, the current implementation must be improved.
The code snippet provided in your question ProfileImagePost
attempts to receive a HttpPostedFile
parameter. However, this approach may not work as expected in ASP.NET Web API.
Instead, use the following pattern to successfully handle file uploads:
<code class="language-csharp">[HttpPost("api/upload")] public async Task<IHttpActionResult> Upload() { if (!Request.Content.IsMimeMultipartContent()) throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); var provider = new MultipartMemoryStreamProvider(); await Request.Content.ReadAsMultipartAsync(provider); foreach (var file in provider.Contents) { var filename = file.Headers.ContentDisposition.FileName.Trim('"'); var buffer = await file.ReadAsByteArrayAsync(); // 使用文件名和二进制数据执行任何操作。 } return Ok(); }</code>
This modified code snippet ensures that you can receive and handle file uploads in ASP.NET Web API by treating the incoming request as multipart data and extracting the file name and file content.
The above is the detailed content of How to Handle File Uploads via POST in ASP.NET Web API?. For more information, please follow other related articles on the PHP Chinese website!