演示如何通过 web api 上传文件
WebApiWebFormHost/UploadFileController.cs/* * 通过 web api 上传文件 */using System;using System.Collections.Generic;using System.Linq;using System.Net;using System.Net.Http;using System.Threading.Tasks;using System.Web.Http;namespace MVC40.Controllers{ public class UploadFileController : ApiController { public async TaskPost() { // 检查是否是 multipart/form-data if (!Request.Content.IsMimeMultipartContent("form-data")) throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); // 设置上传目录 var provider = new MultipartFormDataStreamProvider(@"c:\\temp"); // 接收数据,并保存文件 var bodyparts = await Request.Content.ReadAsMultipartAsync(provider); string result = ""; // 获取表单数据 result += "formData txtName: " + bodyparts.FormData["txtName"]; result += " "; // 获取文件数据 result += "fileData headers: " + bodyparts.FileData[0].Headers; // 上传文件相关的头信息 result += " "; result += "fileData localFileName: " + bodyparts.FileData[0].LocalFileName; // 文件在服务端的保存地址,需要的话自行 rename 或 move return result; } }}
WebApiWebFormHost/UploadDemo.cshtml
@{ Layout = null;}调用 web api 上传文件的 demo @using (Html.BeginForm("UploadFile", "api", FormMethod.Post, new { enctype = "multipart/form-data" })) {please select a file}