应无所住,而生其心
排名
6
文章
6
粉丝
16
评论
8
{{item.articleTitle}}
{{item.blogName}} : {{item.content}}
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2024TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:50010702506256
欢迎加群交流技术

AJAX调用webapi上传图片或文件。设置token,设置Authorization Bearer

9215人阅读 2019/6/21 11:51 总访问:4814054 评论:2 收藏:0 手机
分类: .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('.');
        }
    }

效果如下:

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


如果后台接口需要设置token,设置Authorization Bearer 
通过header设置就行

headers: { 
     "Authorization":"Bearer "+token,
     'Content-Type': 'application/json'  //application/x-www-form-urlencoded  application/json
},

来个例子。
表单

<form id="uploadImgForm" action="http://localhost:8080/apis/oss/api/SmartFiles/UpLoadFormFile" method="post">
    <input type="text" name="bucketName" value="labroom">
    <input type="text" name="filePath" value="labresult">
    <input type="text" name="FileType" value="1">
    <input type="file" name="file">
    <input type="button" value="提交" id="upLoadImgBut">       
</form>

js:

var formData = new FormData($("#uploadImgForm")[0]);
let token = "eyJhbGciOiJSUzI1NiIsImtpZCI6IkU0QUU1RkVFRUQ4ODhFMDAyRjM5ODcwODdGQjZBMDlFQ0UxQ0IzRThSUzI1NiIsInR5cCI6ImF0K2p3dCIsIng1dCI6IjVLNWY3dTJJamdBdk9ZY0lmN2FnbnM0Y3MtZyJ9.eyJuYmYiOjE2NjUyNzg2NTcsImV4cCI6MTY2NTM1MDY1NywiaXNzIjoiaHR0cDovL3RhaS5jcXp1eGlhLmNvbSIsImNsaWVudF9pZCI6IjQzMjE1Y2RmZjJkNTQwN2Y4YWYwNzRkMmQ3ZTU4OWVlIiwic3ViIjoiNTEzOTlmYzljYW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CrPyTwPVJ9pZM6SznLGGgMmBWCT9L3c44ctckEZG00haoJPkaJALYbcW-uevn2DPwCKVLBKvgFxk6cRQkISsq5DoMKts5BKHbWIjHs2MmIDjZuwGEG_5Jshw";
$.ajax({
    url: 'http://localhost:8080/apis/oss/api/SmartFiles/UpLoadFormFile',
    type: 'post',
    data: formData,
    async: false,
    cache: false,
    contentType: false,
    processData: false,
    headers: { 
        "Authorization":"Bearer "+token,
        //'Content-Type': 'application/json'  //application/x-www-form-urlencoded  application/json
    },         
    success: function (returndata) {
        console.log(returndata);
    },
    error: function (returndata) {
        alert("报错了");
        console.log(returndata);
    }
});


欢迎加群讨论技术,群:677373950(满了,可以加,但通过不了),2群:656732739

评价