JS (with Jquery)
//富文本编辑器 $(function () { $('textarea#kcontent1').tinymce({ height: 500, api_key: 'go7j6odzzjf9lix8i5nvsl62tbh0972qe3z6f5kxv4mvamdl', menubar: false, plugins: [ 'advlist', 'autolink', 'lists', 'charmap', 'preview', 'anchor', 'searchreplace', 'visualblocks', 'fullscreen', 'insertdatetime', 'media', 'table', 'help', 'wordcount', 'image', 'codesample', 'code', 'link', 'autosave', ], toolbar: 'undo redo | bold italic forecolor backcolor | link unlink imageupload image codesample code | ' + 'alignleft aligncenter| ' + 'bullist numlist outdent indent | removeformat| restoredraft', language: 'zh_CN', //images_file_types: 'jpg,svg,webp', //image_title: true, //file_picker_types: 'file image media', //images_upload_url: 'Blogs.asmx/UploadImage | submitPage.aspx/UploadImage', images_upload_handler: (blobInfo, progress) => new Promise((resolve, reject) => { const formData = new FormData(); formData.append('file', blobInfo.blob(), blobInfo.filename()); $.ajax({ url: "Blogs.asmx/UploadImage", method: "POST", data: formData, processData: false, // 告诉jQuery不要去处理发送的数据 contentType: false, // 告诉jQuery不要去设置Content-Type请求头 xhr: function () { var xhr = new XMLHttpRequest(); xhr.upload.addEventListener("progress", function (event) { if (event.lengthComputable) { progress(event.loaded / event.total * 100); } }, false); return xhr; }, success: function (data) { var url = data.getElementsByTagName('string')[0].innerHTML; console.log(url); resolve(url); }, error: function (XMLHttpRequest, textStatus, errorThrown) { reject('HTTP Error: ' + textStatus); //reject({ message: 'HTTP Error: ' + xhr.status, remove: true }); showAlert(errorThrown + '请求失败'); }, }); }), }); });
-后端 (ASP.NET) 注意,webconfig要允许ajax(xhr)跨域调用
[WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public string UploadImage() { HttpContext context = HttpContext.Current; HttpPostedFile file = context.Request.Files["file"]; if (file == null || file.ContentLength == 0) { return ""; } else { // 保存路径 String aspxUrl = context.Request.Path.Substring(0, context.Request.Path.LastIndexOf("/") + 1); //根目录路径,相对路径 String saveFolder = aspxUrl + "../../editor/attached"; var baseFolder = context.Server.MapPath(saveFolder); // 日期 String ymd = DateTime.Now.ToString("yyyyMM", DateTimeFormatInfo.InvariantInfo); string uploadFolder = $"{baseFolder}\\{ymd}"; string fileName = Guid.NewGuid().ToString("N") + Path.GetExtension(file.FileName); string filePath = Path.Combine(uploadFolder, fileName); if (!Directory.Exists(uploadFolder)) { Directory.CreateDirectory(uploadFolder); } file.SaveAs(filePath); // 返回图片可访问的URL return $"../editor/attached/{ymd}/{fileName}"; } }