ASP.NET WEB API 上传文件

<form enctype="multipart/form-data">
    <label>
        Using JQuery
    </label>
    <input name="file" type="file" multiple id="me" />
    <input type="button" id="Upload" value="Upload" />
</form>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
    $(function () {
        $('#Upload').click(function () {
            var formData = new FormData();
            var opmlFile = $('#me')[0];
            for (var i = 0; i < opmlFile.files.length; i++) {
                console.log(i);
                formData.append("opmlFile" + i, opmlFile.files[i]);
            }
            $.ajax({
                url: 'http://localhost:3890/api/UploadFile',
                type: 'POST',
                data: formData,
                cache: false,
                contentType: false,
                processData: false
            });
        });
    });
</script>

@{
    ViewBag.Title = "UploadPortrait";
}
<h2>UploadPortrait</h2>
<form method="post" action="/api/UploadFile" 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" />
</form>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Threading.Tasks;
using System.Net.Http.Headers;
using System.IO;
using System.Web;
namespace MDesk.RestfulService.Controllers
{
    public class UploadFileController : ApiController
    {
        public HttpResponseMessage PostFile()
        {
            HttpResponseMessage result = null;
            var httpRequest = HttpContext.Current.Request;
            if (httpRequest.Files.Count > 0)
            {
                var docfiles = new List<string>();
                for (int i = 0; i < httpRequest.Files.Count; i++)
                {
                    var postedFile = httpRequest.Files[i];
                    var filePath = HttpContext.Current.Server.MapPath("~/uploads/" + DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss") + postedFile.FileName.Substring(postedFile.FileName.LastIndexOf('\\') + 1));
                    postedFile.SaveAs(filePath);
                    docfiles.Add(filePath);
                }
                 
                result = Request.CreateResponse(HttpStatusCode.Created, docfiles);
            }
            else
            {
                result = Request.CreateResponse(HttpStatusCode.BadRequest);
            }
            return result;
        }
    }
}


知识共享许可协议
《ASP.NET WEB API 上传文件》常伟华 创作。
采用 知识共享 署名-相同方式共享 3.0 中国大陆 许可协议进行许可。
  • 多说评论
  • 签名
  • 新浪微博
  • 默认评论
  • Tab Header 5

0 条评论 / 点击此处发表评论

Tab Content 5

开发技术


开发平台和工具

sitemap     170.75ms