• 使用summernote编辑器上传图片,重写onImageUpload


    JS部分:
    $('.summernote').summernote({
    height: 200,//高度
    tabsize: 2,//页面上的summernote编辑框的个数
    lang: 'zh-CN',//语言
    callbacks:{//回调函数,重写onImageUpload方法
    onImageUpload: function(files, editor, welEditable) {
    sendFile(this,files[0],editor,welEditable);
    }
    }
    });
    function sendFile(val,files,editor,welEditable) {
    data = new FormData();
    data.append("files", files);
    $.ajax({
    data: data,
    dataType: 'json',
    type: "POST",
    url: "后台url",
    cache: false,
    contentType: false,
    processData: false,
    responseType: "json",
    success: function(data) {
    $(val).summernote('editor.insertImage', data.path);
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
    alert(XMLHttpRequest.status);
    alert(XMLHttpRequest.readyState);
    alert(textStatus);
    }
    });
    }

    springmvc后台:
    @RequestMapping(value = "ajaxUploadFile",produces="application/json;charset=UTF-8")
    @ResponseBody
    public void ajaxUploadFile(@RequestParam("files") CommonsMultipartFile myfiles, HttpServletRequest request,HttpServletResponse response) {

    int size = 0;
    String fileLogicName = "";
    PageData pageData = new PageData();
    UUID uuid = UUID.randomUUID();
    String[] fileNames = myfiles.getOriginalFilename().split("\.");
    String suffix = fileNames[1];
    String fileName = uuid.toString().replace("-", ""); // 文件重命名
    if (fileNames.length >= 2) {
    fileName += "." + fileNames[1];
    }

    String relPath = FilePathUtil.getUploadTempPath(request) + fileName;
    String filePath = FilePathUtil.getFileRootPath(request) + relPath;// 文件保存的实际路径
    File localFile = new File(filePath);
    if (!localFile.getParentFile().exists()) {
    localFile.getParentFile().mkdirs();
    }

    try {
    size = myfiles.getBytes().length;
    fileLogicName = myfiles.getOriginalFilename();
    myfiles.transferTo(localFile); // 保存文件
    } catch (IOException e) {
    pageData.setResult(2);
    pageData.setDesc("上传文件失败");
    logger.error("上传文件失败", e);
    }
    relPath = relPath.replace("\", "/").replace("//", "/");

    pageData.setResult(1);
    pageData.setDesc("文件添加成功!");
    relPath = relPath.replace("\", "/").replace("//", "/");
    FileInfo fileInfo = new FileInfo();
    fileInfo.setFileSize(size);
    fileInfo.setFileName(fileName);
    fileInfo.setFilePath(relPath);
    fileInfo.setSuffix(suffix);
    fileInfo.setFullFileUrl(relPath);
    fileInfo.setFileLogicName(fileLogicName);
    StringBuffer stringBuffer = new StringBuffer();
    stringBuffer.append("{");
    stringBuffer.append(""result"" + ":" + """ + pageData.getResult() + "",");
    stringBuffer.append(""desc"" + ":" + """ + pageData.getDesc() + "",");
    stringBuffer.append(""fileSize"" + ":" + """ + fileInfo.getFileSize() + "",");
    stringBuffer.append(""fileName"" + ":" + """ + fileInfo.getFileName() + "",");
    stringBuffer.append(""filePath"" + ":" + """ + fileInfo.getFilePath() + "",");
    stringBuffer.append(""suffix"" + ":" + """ + fileInfo.getSuffix() + "",");
    stringBuffer.append(""fullFileUrl"" + ":" + """ + fileInfo.getFullFileUrl() + "",");
    stringBuffer.append(""fileLogicName"" + ":" + """ + fileInfo.getFileLogicName() + """);
    stringBuffer.append("}");
    try {
    //response.setContentType("text/javascript");
    response.setContentType("text/html; charset=utf-8");
    response.getWriter().print(stringBuffer.toString());
    } catch (IOException e) {

    }
    }

    FileInfo实体类
    package com.cec.test;
    public class FileInfo {

    private Integer fileSize;

    private String fileName;

    private String filePath;

    private String suffix;

    private String fullFileUrl;

    private String fileLogicName;


    public Integer getFileSize() {
    return fileSize;
    }

    public void setFileSize(Integer fileSize) {
    this.fileSize = fileSize;
    }

    public String getFileName() {
    return fileName;
    }

    public void setFileName(String fileName) {
    this.fileName = fileName;
    }

    public String getFilePath() {
    return filePath;
    }

    public void setFilePath(String filePath) {
    this.filePath = filePath;
    }

    public String getSuffix() {
    return suffix;
    }

    public void setSuffix(String suffix) {
    this.suffix = suffix;
    }

    public String getFullFileUrl() {
    return fullFileUrl;
    }

    public void setFullFileUrl(String fullFileUrl) {
    this.fullFileUrl = fullFileUrl;
    }

    public String getFileLogicName() {
    return fileLogicName;
    }

    public void setFileLogicName(String fileLogicName) {
    this.fileLogicName = fileLogicName;
    }
    }

    FilePathUtil工具类
    public static String  getUploadTempPath(HttpServletRequest request){

    String currentDateStr = DateUtil.sdfDays.format(new Date());
    StringBuffer downloadPath = new StringBuffer();
    downloadPath.append( File.separator).append(FILE_UPLOAD_TEMP_PATH)
    .append(File.separator).append(currentDateStr)
    .append(File.separator);
    // 解决掉前台jsp展示的时候出现 转义字符问题
    String filepath = downloadPath.toString().replace("\", "/").replace("//","/");

    return filepath;
    }
    public static String getRelPath(HttpServletRequest request, String path){
    String filepath = new StringBuffer (getFileRootPath(request)).append(path).toString();
    filepath = filepath.toString().replace("\", "/").replace("//","/");
    File dir = new File(filepath);
    if (!dir.exists()) {
    boolean makeSucess = dir.mkdirs();
    if(!makeSucess){
    logger.error("创建文件目录失败:" + filepath);
    }
    }
    return filepath;
    }
    //PageDate类 
    //用于后台向前台响应ajax请求返回的对象

    @Component
    public class PageData {
    private int result;
    private Map<Object,Object> resultMap;
    private String desc;

    public int getResult() {
    return result;
    }

    public void setResult(int result) {
    this.result = result;
    }

    public Map<Object,Object> getResultMap() {

    //统一分配资源
    if(resultMap == null){
    resultMap = new HashMap<Object,Object>();
    }

    return resultMap;
    }

    public void setResultMap(Map resultMap) {
    this.resultMap = resultMap;
    }

    public String getDesc() {
    return desc;
    }

    public void setDesc(String desc) {
    this.desc = desc;
    }
    }
    展示:



    //UUID类可上网百度获得,工作之后初次使用summernote的使用经验。

    场景:公司项目是一个页面上有两个富文本编辑框,和一个保存按钮
    解决思路:在用户点击图片按钮,上传图片的时候,调用回调函数,将图片通过FormData对象传到后台,后台将图片暂时保存到临时图片文件夹,返回临时图片地址。
    前台接收到图片地址之后,将图片插入到富文本编辑框内。当用户点击保存时,将临时文件夹中的图片保存到真实图片保存目录下(这样做的目的是为了解决维护人员不会把临时文件删除掉,看个人需求)。
    通过summernote('code')获取文本框内的内容,通过ajax传到后台,后台接收到参数之后,使用正则表达式替换掉临时文件夹的目录,最终返回真实图片保存目录,将真实图片保存目录保存到数据库。

    //备注:解决思路中的保存步骤代码在此处没有展示。

    总结:思路很重要,先理清思路,再动手不迟!
    
    


  • 相关阅读:
    【leetcode】974. Subarray Sums Divisible by K
    【leetcode】976. Largest Perimeter Triangle
    【leetcode】973. K Closest Points to Origin
    listen 70
    科学60秒 (一) :上
    listen 69
    listen 68 Theoretical Physicist Stephen Hawking Dies at 76
    中译英33
    listen 67
    中译英32
  • 原文地址:https://www.cnblogs.com/cecWork/p/9173497.html
Copyright © 2020-2023  润新知