WebApiWebFormHost/UploadFileController.cs/* * 通过 web api
上传文件 */using Systemusing System.Collections.Genericusing System.Linqusing System.Netusing System.Net.Httpusing System.Threading.Tasksusing System.Web.Httpnamespace MVC40.Controllers { publicclass UploadFileController : ApiController { publicasync Task<string>Post() { // 检查是否是 multipart/form-dataif (!Request.Content.IsMimeMultipartContent("form-data")) thrownew 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 += "<br />"// 获取文件数据 result += "fileData headers: " + bodyparts.FileData[0].Headers//
上传文件相关的头信息 result += "<br />"result += "fileData localFileName: " + bodyparts.FileData[0].LocalFileName// 文件在服务端的保存地址,需要的话自行 rename 或 movereturn result} } }WebApiWebFormHost/UploadDemo.cshtml@{ Layout = null} <!DOCTYPE html><html><head><title>调用web api 上传文件的 demo</title></head><body>@using (Html.BeginForm("UploadFile", "api", FormMethod.Post, new { enctype = "multipart/form-data" })) { <input type="text" id="txtName" name="txtName" value="webabcd"/><div>please select a file</div><input name="data" type="file" multiple /><input type="submit"/>} </body></html>HttpClient c = new HttpClient()
var fileContent = new ByteArrayContent(new byte[100])
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "myFilename.txt"
}
var formData = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("name", "ali"),
new KeyValuePair<string, string>("title", "ostad")
})
MultipartContent content = new MultipartContent()
content.Add(formData)
content.Add(fileContent)
c.PostAsync(myUrl, content)
评论列表(0条)