演示如何通过 web api 上传文件MVC40

演示如何通过 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 Task<string> Post()

        {

            // 检查是否是 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 += "<br />";



            // 获取文件数据

            result += "fileData headers: " + bodyparts.FileData[0].Headers; // 上传文件相关的头信息

            result += "<br />";

            result += "fileData localFileName: " + bodyparts.FileData[0].LocalFileName; // 文件在服务端的保存地址,需要的话自行 rename 或 move



            return 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>
复制代码

你可能感兴趣的:(上传文件)