1. 程式人生 > >springboot 整合umeditor,上傳圖片

springboot 整合umeditor,上傳圖片

1.把資料夾copy到專案的靜態資源目錄下

image

其中jsp資料夾全部刪除了,因為springboot直接訪問jsp會攔截,所以jsp都改造成java了。

2.引入JAR包

ueditor-mini.jar不需要引用,因為裡面只包含一個uploader.java,我們要修改這個檔案

<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version
>
1.2.2</version> </dependency>

3.頁面引用js和css

<link href="/my/js/ueditor/themes/default/css/umeditor.css" type="text/css" rel="stylesheet">
<script type="text/javascript" src="/my/js/ueditor/umeditor.config.js"></script>
<script type="text/javascript" src="/my/js/ueditor/umeditor.min.js"
>
</script> <script type="text/javascript" src="/my/js/ueditor/lang/zh-cn/zh-cn.js"></script>

因為我的springboot靜態資源訪問路徑是/my/**,所以路徑前面都會加個/my

mvc:
    view:
      prefix: /WEB-INF/view/
      suffix: .jsp
    # 修改靜態資源訪問路徑  預設值為 /**
    static-path-pattern: /my/**

4.頁面呼叫

<script type="text/plain"
id="school_add_editor">
</script> <script type="text/javascript"> var schoolAddEditor = UM.getEditor('school_add_editor'); </script>

5.重點,上傳圖片配置

1.修改Uploader.java,增加upload(MultipartFile upfile)方法,修改getPhysicalPath()方法

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.FileUploadBase.InvalidContentTypeException;
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.util.*;
import org.apache.commons.fileupload.servlet.*;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;


import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;
import javax.servlet.http.HttpServletRequest;
/**
 * UEditor檔案上傳輔助類
 *
 */
public class Uploader {
    // 輸出檔案地址
    private String url = "";
    // 上傳檔名
    private String fileName = "";
    // 狀態
    private String state = "";
    // 檔案型別
    private String type = "";
    // 原始檔名
    private String originalName = "";
    // 檔案大小
    private long size = 0;

    private HttpServletRequest request = null;
    private String title = "";

    // 儲存路徑
    private String savePath = "upload";
    // 檔案允許格式
    private String[] allowFiles = { ".rar", ".doc", ".docx", ".zip", ".pdf",".txt", ".swf", ".wmv", ".gif", ".png", ".jpg", ".jpeg", ".bmp" };
    // 檔案大小限制,單位KB
    private int maxSize = 10000;

    private HashMap<String, String> errorInfo = new HashMap<String, String>();

    public Uploader(HttpServletRequest request) {
        this.request = request;
        HashMap<String, String> tmp = this.errorInfo;
        tmp.put("SUCCESS", "SUCCESS"); //預設成功
        tmp.put("NOFILE", "未包含檔案上傳域");
        tmp.put("TYPE", "不允許的檔案格式");
        tmp.put("SIZE", "檔案大小超出限制");
        tmp.put("ENTYPE", "請求型別ENTYPE錯誤");
        tmp.put("REQUEST", "上傳請求異常");
        tmp.put("IO", "IO異常");
        tmp.put("DIR", "目錄建立失敗");
        tmp.put("UNKNOWN", "未知錯誤");

    }

    /**
     * 重寫upload方法,解決訪問controller中的上傳方法時獲取不到上傳檔案的問題
     * @param upfile
     * @throws Exception
     */
    public void upload(MultipartFile upfile) throws Exception {
        if (upfile == null) {
            this.state = this.errorInfo.get("NOFILE");
            return;
        }
        String savePath = this.getFolder(this.savePath);
        try {
            this.originalName = upfile.getOriginalFilename().substring(upfile.getOriginalFilename().lastIndexOf(System.getProperty("file.separator")) + 1);
            if (!this.checkFileType(this.originalName)) {
                this.state = this.errorInfo.get("TYPE");
                return;
            }
            this.fileName = this.getName(this.originalName);
            this.type = this.getFileExt(this.fileName);
            this.url = savePath + "/" + this.fileName;
            BufferedInputStream in = new BufferedInputStream(upfile.getInputStream());
            File file = new File(this.getPhysicalPath(this.url));
            FileOutputStream out = new FileOutputStream( file );
            BufferedOutputStream output = new BufferedOutputStream(out);
            Streams.copy(in, output, true);
            this.state=this.errorInfo.get("SUCCESS");
            this.size = file.length();

        } catch (Exception e) {
            this.state = this.errorInfo.get("UNKNOWN");
        }
    }


    public void upload() throws Exception {
        boolean isMultipart = ServletFileUpload.isMultipartContent(this.request);
        if (!isMultipart) {
            this.state = this.errorInfo.get("NOFILE");
            return;
        }
        DiskFileItemFactory dff = new DiskFileItemFactory();
        String savePath = this.getFolder(this.savePath);
        dff.setRepository(new File(savePath));
        try {
            ServletFileUpload sfu = new ServletFileUpload(dff);
            sfu.setSizeMax(this.maxSize * 1024);
            sfu.setHeaderEncoding("utf-8");
            FileItemIterator fii = sfu.getItemIterator(this.request);
            while (fii.hasNext()) {
                FileItemStream fis = fii.next();
                if (!fis.isFormField()) {
                    this.originalName = fis.getName().substring(fis.getName().lastIndexOf(System.getProperty("file.separator")) + 1);
                    if (!this.checkFileType(this.originalName)) {
                        this.state = this.errorInfo.get("TYPE");
                        continue;
                    }
                    this.fileName = this.getName(this.originalName);
                    this.type = this.getFileExt(this.fileName);
                    this.url = savePath + "/" + this.fileName;
                    BufferedInputStream in = new BufferedInputStream(fis.openStream());
                    File file = new File(this.getPhysicalPath(this.url));
                    FileOutputStream out = new FileOutputStream( file );
                    BufferedOutputStream output = new BufferedOutputStream(out);
                    Streams.copy(in, output, true);
                    this.state=this.errorInfo.get("SUCCESS");
                    this.size = file.length();
                    //UE中只會處理單張上傳,完成後即退出
                    break;
                } else {
                    String fname = fis.getFieldName();
                    //只處理title,其餘表單請自行處理
                    if(!fname.equals("pictitle")){
                        continue;
                    }
                    BufferedInputStream in = new BufferedInputStream(fis.openStream());
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                    StringBuffer result = new StringBuffer();  
                    while (reader.ready()) {  
                        result.append((char)reader.read());  
                    }
                    this.title = new String(result.toString().getBytes(),"utf-8");
                    reader.close();  

                }
            }
        } catch (SizeLimitExceededException e) {
            this.state = this.errorInfo.get("SIZE");
        } catch (InvalidContentTypeException e) {
            this.state = this.errorInfo.get("ENTYPE");
        } catch (FileUploadException e) {
            this.state = this.errorInfo.get("REQUEST");
        } catch (Exception e) {
            this.state = this.errorInfo.get("UNKNOWN");
        }
    }

    /**
     * 接受並儲存以base64格式上傳的檔案
     * @param fieldName
     */
    public void uploadBase64(String fieldName){
        String savePath = this.getFolder(this.savePath);
        String base64Data = this.request.getParameter(fieldName);
        this.fileName = this.getName("test.png");
        this.url = savePath + "/" + this.fileName;
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            File outFile = new File(this.getPhysicalPath(this.url));
            OutputStream ro = new FileOutputStream(outFile);
            byte[] b = decoder.decodeBuffer(base64Data);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            ro.write(b);
            ro.flush();
            ro.close();
            this.state=this.errorInfo.get("SUCCESS");
        } catch (Exception e) {
            this.state = this.errorInfo.get("IO");
        }
    }

    /**
     * 檔案型別判斷
     * 
     * @param fileName
     * @return
     */
    private boolean checkFileType(String fileName) {
        Iterator<String> type = Arrays.asList(this.allowFiles).iterator();
        while (type.hasNext()) {
            String ext = type.next();
            if (fileName.toLowerCase().endsWith(ext)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 獲取副檔名
     * 
     * @return string
     */
    private String getFileExt(String fileName) {
        return fileName.substring(fileName.lastIndexOf("."));
    }

    /**
     * 依據原始檔名生成新檔名
     * @return
     */
    private String getName(String fileName) {
        Random random = new Random();
        return this.fileName = "" + random.nextInt(10000)
                + System.currentTimeMillis() + this.getFileExt(fileName);
    }

    /**
     * 根據字串建立本地目錄 並按照日期建立子目錄返回
     * @param path 
     * @return 
     */
    private String getFolder(String path) {
        SimpleDateFormat formater = new SimpleDateFormat("yyyyMMdd");
        path += "/" + formater.format(new Date());
        File dir = new File(this.getPhysicalPath(path));
        if (!dir.exists()) {
            try {
                dir.mkdirs();
            } catch (Exception e) {
                this.state = this.errorInfo.get("DIR");
                return "";
            }
        }
        return path;
    }

    /**
     * 根據傳入的虛擬路徑獲取物理路徑
     * 
     * @param path
     * @return
     */
    private String getPhysicalPath(String path) {
        /*String servletPath = this.request.getServletPath();
        String realPath = this.request.getSession().getServletContext()
                .getRealPath(servletPath);
        return new File(realPath).getParent() +"/" +path;*/
        return this.request.getSession().getServletContext().getRealPath("/") + path;
    }

    public void setSavePath(String savePath) {
        this.savePath = savePath;
    }

    public void setAllowFiles(String[] allowFiles) {
        this.allowFiles = allowFiles;
    }

    public void setMaxSize(int size) {
        this.maxSize = size;
    }

    public long getSize() {
        return this.size;
    }

    public String getUrl() {
        return this.url;
    }

    public String getFileName() {
        return this.fileName;
    }

    public String getState() {
        return this.state;
    }

    public String getTitle() {
        return this.title;
    }

    public String getType() {
        return this.type;
    }

    public String getOriginalName() {
        return this.originalName;
    }
}

2.把imageUp.jsp改造成controller

@RestController
public class UploadController {

    @RequestMapping("/uploadUEImage")
    public String uploadUEImage(MultipartFile upfile,HttpServletRequest request) throws Exception{
        Uploader up = new Uploader(request);
        up.setSavePath("/upload");
        String[] fileType = {".gif" , ".png" , ".jpg" , ".jpeg" , ".bmp"};
        up.setAllowFiles(fileType);
        up.setMaxSize(10000); //單位KB
        up.upload(upfile);

        String callback = request.getParameter("callback");
        String result = "{\"name\":\""+ up.getFileName() +"\", \"originalName\": \""+ up.getOriginalName() +"\", \"size\": "+ up.getSize()
                +", \"state\": \""+ up.getState() +"\", \"type\": \""+ up.getType() +"\", \"url\": \""+ up.getUrl() +"\"}";

        result = result.replaceAll( "\\\\", "\\\\" );
        if(callback == null ){
            return result ;
        }else{
            return "<script>"+ callback +"(" + result + ")</script>";
        }
    }
}

3.修改umeditor.config.js

,imageUrl: "/uploadUEImage"             //圖片上傳提交地址
,imagePath: "/my"             //圖片修正地址,引用了fixedImagePath,如有特殊需求,可自行配置(springboot靜態資源字首)