asp.net core 通過ajax上傳圖片
.net core前端代碼,因為是通過ajax調用,首先要保證ajax能調用后台代碼,具體參見上一篇.net core 使用ajax調用后台代碼。
前端代碼如下:
@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>
后端代碼:
[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指定了一個文件夾,沒有包括文件名稱,沒有指定具體的路徑,一直報錯
提示:路徑訪問禁止,access deny...,文件夾的所有權限都改了(添加net work 、IIS User),還是不行..。坑啊,改成完整路徑就可以了。
另外,在后台代碼沒有設置為異步時出現問題,在進行圖片上傳時,重新運行程序后,第一張可以上傳成功,然后再上傳,傳到服務端的圖片大小為0。
代碼設置為異步后,問題解決
結合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一系列的。