asp.net core 經過ajax上傳圖片及wangEditor圖片上傳

asp.net core 經過ajax上傳圖片

.net core前端代碼,由於是經過ajax調用,首先要保證ajax能調用後臺代碼,具體參見上一篇.net core 使用ajax調用後臺代碼。javascript

前端代碼以下:前端

@Html.AntiForgeryToken()   
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<div>
        <form id="uploadForm">
            AJAX上傳多文件: <input type="file" name="file" multiple />
            <input type="button" value="上傳" onclick="doUpload()" />
        </form>
    </div>
    <script>
        function doUpload() {
            var formData = new FormData($("#uploadForm")[0]);
            $.ajax({
                  url: "Train?handler=Upload",
                beforeSend: function (xhr) {
                    xhr.setRequestHeader("XSRF-TOKEN",
                        $('input:hidden[name="__RequestVerificationToken"]').val());
                },
                type: 'POST',
                data: formData,
                async: false,
                cache: false,
                contentType: false,
                processData: false,
                success: function (returndata) {
                    alert(returndata);
                },
                error: function (returndata) {
                    alert(returndata);
                }
            });
        }
    </script>

 

後端代碼:java

 [HttpPost]
        public async Task<IActionResult> OnPostUpload([FromServices]IHostingEnvironment environment)
        {
            List<TmpUrl> list = new List<TmpUrl>();
            var files = Request.Form.Files;
            string webRootPath = environment.WebRootPath;
            string contentRootPath = environment.ContentRootPath;
            foreach (var formFile in files)
            {
                if (formFile.Length > 0)
                {
                    var fileName = Guid.NewGuid().ToString()+".jpg";
                    var path = Path.Combine(environment.WebRootPath + "\\images\\upload", fileName);
                    using (var stream = new FileStream(path, FileMode.CreateNew))  
                    {
                        await formFile.CopyToAsync(stream);
                        TmpUrl tu = new TmpUrl();
                        tu.Url = @"/images/upload/"+ fileName;
                        list.Add(tu);
                    }
                }
            }
            
            return new JsonResult(list);

        }

注:var stream = new FileStream(path, FileMode.CreateNew,開始這裏的path指定了一個文件夾,沒有包括文件名稱,沒有指定具體的路徑,一直報錯jquery

提示:路徑訪問禁止,access deny...,文件夾的全部權限都改了(添加net work 、IIS User),仍是不行..。坑啊,改爲完整路徑就能夠了。web

另外,在後臺代碼沒有設置爲異步時出現問題,在進行圖片上傳時,從新運行程序後,第一張能夠上傳成功,而後再上傳,傳到服務端的圖片大小爲0。ajax

代碼設置爲異步後,問題解決後端

 結合wangEditor圖片上傳接口

這裏是使用自定義的圖片上傳接口,具體實現就是上面的,而後返回圖片的url,調用wangEditor裏的insert(imageUrl)方法在文本編輯器中插入圖片。服務器

後端代碼和就是上面那一段後端代碼,前端代碼以下:網絡

<head>
    <meta charset="UTF-8">
    <title>wangEditor demo</title>
    <script src="~/js/wangEditor.js"></script>
    <script src="~/js/jquery.js"></script>
</head>
<div id="editor">
        <p>歡迎使用 <b>wangEditor</b> 富文本編輯器</p>
    </div>
    
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
    <script type="text/javascript">
        var E = window.wangEditor;
        var editor = new E('#editor');

        //editor.customConfig.uploadImgServer = 'Train?handler=Upload'; //上傳URL
        editor.customConfig.uploadImgMaxSize = 3 * 1024 * 1024;
        editor.customConfig.uploadImgMaxLength = 5;
        //editor.customConfig.uploadFileName = 'myFileName';

        editor.customConfig.customUploadImg = function (files, insert) {
            // files 是 input 中選中的文件列表
            // insert 是獲取圖片 url 後,插入到編輯器的方法
            var uploadData = new FormData();
            for (var i = 0; i < files.length; i++) {
                uploadData.append(files[i].name, files[i]);
            }

            $.ajax({
                type: "POST",
                url: "Train?handler=Upload",
                beforeSend: function (xhr) {
                    xhr.setRequestHeader("XSRF-TOKEN",
                        $('input:hidden[name="__RequestVerificationToken"]').val());
                },
                data: uploadData,
                processData: false,
                contentType: false,
                async: false,
                success: function (response) {
                    alert(response);
                    for (var i = 0; i < response.length; i++) {
                        insert(response[i].url);
                    }
                },
                failure: function (response) {
                    alert(response);
                }
            });
          
            //editor.customConfig.uploadImgHooks = {
            //    customInsert: function (insertImg, result, editor) {
            //        // 圖片上傳並返回結果,自定義插入圖片的事件(而不是編輯器自動插入圖片!!!)
            //        // insertImg 是插入圖片的函數,editor 是編輯器對象,result 是服務器端返回的結果

            //        // 舉例:假如上傳圖片成功後,服務器端返回的是 {url:'....'} 這種格式,便可這樣插入圖片:
            //        for (var i = 0; i < length; i++) {

            //        }
            //        //var url = result.data;
            //        //insertImg(url);

            //        // result 必須是一個 JSON 格式字符串!!!不然報錯
            //    }
            //}
            // 經過 url 參數配置 debug 模式。url 中帶有 wangeditor_debug_mode=1 纔會開啓 debug 模式
            editor.customConfig.debug = location.href.indexOf('wangeditor_debug_mode=1') > 0;
            //editor.customConfig.uploadImgShowBase64 = true   // 使用 base64 保存圖片

            // 上傳代碼返回結果以後,將圖片插入到編輯器中
            //insert(imgUrl)
        }

        editor.create();
    </script>

wangEditor

這個文本編輯器能夠上傳本地圖片、網絡圖片,上傳本地圖片按鈕默認是不顯示的,只有在配置中啓用了本地上傳相關配置才顯示,  editor.customConfig一系列的。app

相關文章
相關標籤/搜索