tnblog
首页
登录

AJAX调用webapi上传图片或文件

261人阅读 2019/6/21 11:51 评论:2 手机 收藏 关注
分类: .NET MVC


AJAX调用webapi上传图片或文件,并返回刚上传的文件名。废话不多说直接贴代码吧


html相关:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <script>
        function doUpload() {
            var formData = new FormData($("#uploadForm")[0]);
            $.ajax({
                url: '/api/upload',
                type: 'post',
                data: formData,
                async: false,
                cache: false,
                contentType: false,
                processData: false,
                success: function (returndata) {
                    alert(returndata);
                },
                error: function (returndata) {
                    alert("报错了");
                    console.log(returndata);
                }
            });
        }
    </script>
</head>
<body>
    <form id="uploadForm">
        <p>无刷新测试: <input type="text" name="filename" value="" /></p>
        <p>上传文件: <input type="file" name="file" /></p>
        <input type="button" value="上传" onclick="doUpload()" />
    </form>
</body>
</html>

webapi相关:

  public async Task<string> Post()
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }
            string uploadFolderPath = HostingEnvironment.MapPath("~/Upload");

            //如果路径不存在,创建路径
            if (!Directory.Exists(uploadFolderPath))
                Directory.CreateDirectory(uploadFolderPath);

            string guid = Guid.NewGuid().ToString().Replace("-","");

            List<string> files = new List<string>();
            var provider = new WithExtensionMultipartFormDataStreamProvider(uploadFolderPath, guid);
            try
            {
                // Read the form data.
                await Request.Content.ReadAsMultipartAsync(provider);

                // This illustrates how to get the file names.

                foreach (var file in provider.FileData)
                {//接收文件
                    files.Add(Path.GetFileName(file.LocalFileName));
                }
            }
            catch
            {
                throw;
            }
            return string.Join(",", files);
        }

其中的WithExtensionMultipartFormDataStreamProvider类:

 public class WithExtensionMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
    {
        public string guid { get; set; }

        public WithExtensionMultipartFormDataStreamProvider(string rootPath, string guidStr)
            : base(rootPath)
        {
            guid = guidStr;
        }

        public override string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers)
        {
            string extension = !string.IsNullOrWhiteSpace(headers.ContentDisposition.FileName) ? Path.GetExtension(GetValidFileName(headers.ContentDisposition.FileName)) : "";
            return guid + extension;
        }

        private string GetValidFileName(string filePath)
        {
            char[] invalids = System.IO.Path.GetInvalidFileNameChars();
            return String.Join("_", filePath.Split(invalids, StringSplitOptions.RemoveEmptyEntries)).TrimEnd('.');
        }
    }

效果如下:

图片与文件被成功上传了:




评价
很多事不是看到了希望才去努力,而是努力了才能看到希望
文章
6
粉丝
16
评论
8
分类
16
{{item.ArticleTitle}}
{{item.BlogName}} : {{item.Content}}