编辑器上传图片一样平常都是先上传到服务器中,若是用户取消或忘记提交表单就产生一张废图在空间内里,时间一长就产生大量占用空间的无用图片,现在就试试提交前先用base64,提交后,在后台处理编辑器内容中的标签src中的base64图片(保存成图片文件并返回相对所在字符串更换原来的base64编码图片,测试在新的TinyMCE编辑器(Version: 5.0.12 (2019-07-18))通过。欣赏器为chrome
代码:
- tinymce.init({
- selector: 'textarea#Content',
- plugins: 'print preview searchreplace autolink directionality visualblocks visualchars fullscreen image link media template code codesample table charmap hr pagebreak nonbreaking anchor insertdatetime advlist lists wordcount imagetools textpattern help paste emoticons autosave ',
- toolbar: 'code undo redo restoredraft | cut copy paste pastetext | forecolor backcolor bold italic underline strikethrough link anchor | alignleft aligncenter alignright alignjustify outdent indent | \
- styleselect formatselect fontselect fontsizeselect | bullist numlist | blockquote subscript superscript removeformat | \
- table image media charmap emoticons hr pagebreak insertdatetime print preview | fullscreen',
- menubar: false,
- height: 500,
- language: 'zh_CN',
- images_upload_handler: function (blobInfo, success, failure) {
- var reader = new FileReader();
- reader.readAsDataURL(blobInfo.blob());
- reader.onload = function () {
- success(this.result);
- }
- }
- });
复制代码
plugins插件及toolbar工具栏内容自行删减添加,紧张是 images_upload_handler这里,不知是TinyMCE5.x版本很强盛,照旧欣赏器本身功能,编辑器中会自动base64编码与blob:http://协议互转。你在源码上看到的是非base64编码
后台用到Regex类Replace方法的高级用法:此方法有个委托参数,用这参数可以传入一个方法,在这个方法内里举行紧张操纵(保存base64到空间中并返回图片所在的引用字符串)
后台asp.net(c#)代码:
- public static string SaveBase64ToImageAndOutUrl(string htmlContent)
- {
- // 界说正则表达式用来匹配 img 标签 src属性中的base64代码
- string strImg = @"data\:image/(jpeg|png|gif|jpg|bmp);base64\,(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?";
- string content = Regex.Replace(htmlContent, strImg, new MatchEvaluator(CorrectString), RegexOptions.Compiled | RegexOptions.IgnoreCase);
- return content;
- }
- private static string CorrectString(Match match)
- {
- string imgSrc = match.Value;
- if (imgSrc.Substring(0, 10) != "data:image")
- return imgSrc;
- double size = imgSrc.Split(',')[1].TrimEnd('=').Length * .75;<br />
- if (size > Config.SiteConfig.ImageUploadSize * 1048576)
- throw new Exception("内容中有些图片过大!");
- Response rsp = Upload.Base64ToImageAndSave(imgSrc, "/Upload");
- if (rsp.Code == 0)
- throw new Exception(rsp.Message);
- return rsp.Data;
- }
复制代码
上面代码涉及到的类Respones
- public class Response
- {
- /// <summary>
- /// 返回代码. 0-失败,1-成功
- /// </summary>
- public int Code { get; set; }
- /// <summary>
- /// 返回消息
- /// </summary>
- public string Message { get; set; }
- /// <summary>
- /// 返回数据
- /// </summary>
- public dynamic Data { get; set; }
- public Response()
- {
- Code = 0;
- }
- }
复制代码
上面的base64保存图片的方法,请参考博客园里其他大侠写的,好多好多,我就不再贴上来了
缺点就是客户端查察源代码时会很慢,另外图片多或图片大时提交数据时要在web.config中设置,不然提交不了。这里设置了6MB,可以根据需要设置大小
- <system.web>
- <!-- 表单提交处理总长度(maxRequestLength)为6MB -->
- <httpRuntime maxRequestLength="6291456"/>
- </system.web>
复制代码
来源:https://www.cnblogs.com/wujiying/p/Base64UploadImage.html |