码迷,mamicode.com
首页 > Windows程序 > 详细

WebApi实现Ajax模拟Multipart/form-data方式多文件上传

时间:2017-08-25 14:04:12      阅读:234      评论:0      收藏:0      [点我收藏+]

标签:end   ram   request   cancel   sda   fun   exists   orm   ssd   

前端页面代码:

<input type="file" class="file_control" /><br />
<input type="file" class="file_control" /><br />
<input type="file" class="file_control" />
<button id="btnUpload" type="button">上传</button>

<script type="text/javascript">

    $(document).ready(function () {
        $("#btnUpload").click(function () {
            var formdata = new FormData();
            var files = $(".file_control");
            $.each(files, function (index, domEle) {
                formdata.append("file" + index, domEle.files[0]);
            });

            $.ajax({
                url: /api/Service/UpLoad,
                type: POST,
                cache: false,
                data: formdata,
                processData: false,
                contentType: false,
                success: function (data) {
                    alert(data.success);
                },
                error: function () {
                    alert("error");
                }
            }).done(function (res) {

            }).fail(function (res) {

            });
        });
</script>

后端代码:

        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("api/Service/UpLoad")]
        public Task<HttpResponseMessage> UpLoad(HttpRequestMessage request)
        {
            if (!request.Content.IsMimeMultipartContent())
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            if (!ModelState.IsValid)
                throw new HttpResponseException(HttpStatusCode.BadRequest);

            string root = AppDomain.CurrentDomain.BaseDirectory + @"UploadFiles";
            if (!Directory.Exists(root))
                Directory.CreateDirectory(root);

            MultipartFormDataStreamProvider provider = new MultipartFormDataStreamProvider(root);

            var task = request.Content.ReadAsMultipartAsync(provider).ContinueWith<HttpResponseMessage>(t =>
            {
                if (t.IsFaulted || t.IsCanceled)
                    return request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception);

                HttpResponseMessage response = null;

                string filePath = root + @"\" + DateTime.Now.ToString("yyyyMMdd");
                if (!Directory.Exists(filePath))
                    Directory.CreateDirectory(filePath);

                foreach (var file in provider.FileData)
                {
                    string fileName = file.Headers.ContentDisposition.FileName;
                    
                    if (Regex.IsMatch(fileName, @"^"".*""$"))
                        fileName = fileName.Trim(");

                    if (Regex.IsMatch(fileName, @"[\\/]+"))
                        fileName = Path.GetFileName(fileName);
                    
                    string extName = Path.GetExtension(fileName);
                    string tempName = DateTime.Now.Ticks.ToString() + extName;
                    File.Copy(file.LocalFileName, Path.Combine(filePath, tempName));

                    if (File.Exists(file.LocalFileName))
                        File.Delete(file.LocalFileName);

                    // 转存阿里OSS、七牛云、腾讯云COS

                    response = request.CreateResponse(HttpStatusCode.OK, new { success = true });
                }

                return response;
            });

            return task;
        }

*注:如果报IsFaulted=true的错误,基本上是因为你没给input起name造成的。

 

WebApi实现Ajax模拟Multipart/form-data方式多文件上传

标签:end   ram   request   cancel   sda   fun   exists   orm   ssd   

原文地址:http://www.cnblogs.com/sheng9hhd/p/7427164.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!