zoukankan      html  css  js  c++  java
  • WebApi实现Ajax模拟Multipart/form-data方式多文件上传

    前端页面代码:

    <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造成的。

  • 相关阅读:
    CentOS7_装机软件推荐
    http://www.osyunwei.com/archives/4788.html
    SQL经典面试题集锦
    异步方式
    webwxgetcontact 获取的是通讯录里的群或好友的信息
    perl 微信取自己的ID
    perl weixin 发消息接口 webwxsendmsg
    Invalid project description.
    运行期间id是不变的
    关于微信 init接口返回的Count和webwxbatchgetcontact post请求的参数Count
  • 原文地址:https://www.cnblogs.com/sheng9hhd/p/7427164.html
Copyright © 2011-2022 走看看