富文本編輯器圖片上傳(跨域解決)(umeditor版本):


端:umeditor.config.js默認不需要修改

      Image.js修改submit方法(用於解決請求跨域的問題):

submit: function (callback) {

    var me = this,
        input = $( '<input style="filter: alpha(opacity=0);" class="edui-image-file" type="file" hidefocus="" name="upfile" accept="image/gif,image/jpeg,image/png,image/jpg,image/bmp">'),
        input = input[0];

    $(me.dialog).delegate( ".edui-image-file", "change", function ( e ) {
        if ( !this.parentNode ) {
            return;
        }
        var xhr = new XMLHttpRequest();
        xhr.open("post", me.editor.getOpt('imageUrl') + "?type=ajax", true);
        //xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
        var fd = new FormData();
        fd.append(me.editor.getOpt('imageFieldName'), event.target.files[0]);
        xhr.send(fd);
        xhr.addEventListener('load', function (e) {
            var r = e.target.response, json;
            me.uploadComplete(r);
            $(this).unbind('load');
            $(this).remove();
        });
        Upload.updateInput( input );
        me.toggleMask("Loading....");
        callback && callback();
    });
    return me;
},

Html:

<!--style給定寬度可以影響編輯器的最終寬度-->
<div class="layui-form-item" id="addPowersToDocumentPage" style="display:none;">
    <form class="layui-form layui-form-pane" action="" lay-filter="addPowersToDocumentForm"
          id="addPowersToDocumentForm">
        <input type="hidden" name="documentId"/>
        <div type="text/plain" id="addPowersToDocument" name="content" style="width:1000px;height:240px;">
        </div>
        <div class="layui-form-item">
            <button type="button" id="addPowersToDocumentSubmit" lay-filter="addPowersToDocumentSubmit"
                    style="display:none" lay-submit></button>
        </div>
    </form>
</div>


<script type="text/javascript">
    window.UMEDITOR_HOME_URL = servicePath + "/back/upload/";
    //實例化編輯器
    var um = UM.getEditor('addPowersToDocument', {
        imageUrl: servicePath + '/back/upload?charset=utf-8&loginCode=' + adminInfo.loginCode, /**圖片上傳執行action**/
        imagePath: servicePath, /**圖片網絡顯示路徑**/
        focus: true
    });
    var umEdit = UM.getEditor('addPowersToDocumentEdit', {
        imageUrl: servicePath + '/back/upload', /**圖片上傳執行action**/
        imagePath: servicePath, /**圖片網絡顯示路徑**/
        focus: true
    });
    var umView = UM.getEditor('addPowersToDocumentView', {
        imageUrl: servicePath + '/back/upload', /**圖片上傳執行action**/
        imagePath: servicePath, /**圖片網絡顯示路徑**/
        focus: true
    });
</script>

控制層:

 

package com.greathack.homlin.controller.docDistribute;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping(value = "/back")
public class UploadController {

    // 輸出文件地址
    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 UploadController() {
    }

    public UploadController(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", "未知錯誤");

    }

    @ResponseBody
    @RequestMapping(value = "/upload")
    public void upload1(HttpServletRequest request, HttpServletResponse response) throws Exception {


        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        UploadController up = new UploadController(request);
        up.setSavePath("/upload");
        String[] fileType = {".gif", ".png", ".jpg", ".jpeg", ".bmp"};
        up.setAllowFiles(fileType);
        up.setMaxSize(10000); //單位KB
        up.upload();

        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) {
            response.getWriter().print(result);
        } else {

            response.getWriter().print("<script>" + callback + "(" + result + ")</script>");
        }
    }

    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(request.getSession().getServletContext().getRealPath(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;
                    //mkdirs(request.getSession().getServletContext().getRealPath(savePath));
                    BufferedInputStream in = new BufferedInputStream(fis.openStream());
                    File file = new File((this.url));
                    FileOutputStream out = new FileOutputStream(file);
                    BufferedOutputStream output = new BufferedOutputStream(out);
                    Streams.copy(in, output, true);
                    this.url = this.savePath + "/" + new SimpleDateFormat("yyyyMMdd").format(new Date()) + "/" + this.fileName;
                    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 (FileUploadBase.SizeLimitExceededException e) {
            this.state = this.errorInfo.get("SIZE");
        } catch (FileUploadBase.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((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;
    }

    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;
    }

}

 

需要注意的是:

Spring-mvc.xml需要對請求的路徑進行放行(三個攔截器都要放行)

<mvc:interceptors>
   <mvc:interceptor>
       <mvc:mapping path="/**"/>
          <mvc:exclude-mapping path="/error/**"/> 
          <mvc:exclude-mapping path="/resources/**"/> 
          <mvc:exclude-mapping path="/static/**"/> 
          <mvc:exclude-mapping path="/upload/**"/> 
          <mvc:exclude-mapping path="/outputfile/**"/> 
          <mvc:exclude-mapping path="/token/getToken"/>
           <mvc:exclude-mapping path="/user/login"/>               
           <mvc:exclude-mapping path="/**/delete"/>               
           <mvc:exclude-mapping path="/**/get**"/>
<mvc:exclude-mapping path="/back/upload"/>
         <bean class="com.greathack.homlin.interceptor.TokenCheckInterceptor"></bean>
        
     </mvc:interceptor>
   <mvc:interceptor>
       <mvc:mapping path="/**"/>
          <mvc:exclude-mapping path="/error/**"/> 
          <mvc:exclude-mapping path="/resources/**"/> 
          <mvc:exclude-mapping path="/static/**"/> 
          <mvc:exclude-mapping path="/upload/**"/> 
          <mvc:exclude-mapping path="/outputfile/**"/> 
          <mvc:exclude-mapping path="/token/getToken"/>
          <mvc:exclude-mapping path="/user/login"/>
<mvc:exclude-mapping path="/back/upload"/>
         <bean class="com.greathack.homlin.interceptor.LoginCodeCheckInterceptor"></bean>
     </mvc:interceptor>
   <mvc:interceptor>
       <mvc:mapping path="/**"/>
          <mvc:exclude-mapping path="/error/**"/> 
          <mvc:exclude-mapping path="/resources/**"/> 
          <mvc:exclude-mapping path="/static/**"/> 
          <mvc:exclude-mapping path="/upload/**"/> 
          <mvc:exclude-mapping path="/outputfile/**"/> 
          <mvc:exclude-mapping path="/token/getToken"/>
 <mvc:exclude-mapping path="/user/login"/>
 <mvc:exclude-mapping path="/user/logout"/>
 <mvc:exclude-mapping path="/user/getLoginInfo"/>
          <mvc:exclude-mapping path="/dict/getAllDict"/>
         <mvc:exclude-mapping path="/dict/getAllDictList"/>
          <mvc:exclude-mapping path="/amUnit/getAmUnitObject"/>
          <mvc:exclude-mapping path="/powerItem/search"/>
          <mvc:exclude-mapping path="/amZlProcess/**"/>
<mvc:exclude-mapping path="/process/**"/>
          <mvc:exclude-mapping path="/*/get*Roster"/>
          <mvc:exclude-mapping path="/amGwgzbz/findByGwjb"/>
<mvc:exclude-mapping path="/amXjgzbz/findByXj"/>
<mvc:exclude-mapping path="/amArchiveAdvSearch/**"/><!--人員高級搜索-->
<mvc:exclude-mapping path="/user/updateSelf"/><!--修改個人資料-->
<mvc:exclude-mapping path="/user/mdfyOwnPwd"/><!--修改自己的密碼-->
<mvc:exclude-mapping path="/console/hometowns"/><!--首頁-->
<mvc:exclude-mapping path="/innerMessage/**"/><!--站內信-->
<mvc:exclude-mapping path="/receive/**"/><!--站內信-->
<mvc:exclude-mapping path="/amHmd/isIdcardInHmd"/><!--判斷是否在黑名單-->
<mvc:exclude-mapping path="/amJbxx/isExist"/><!--判斷是否存在系統中-->
<mvc:exclude-mapping path="/amZlxpc/isHandleComplete"/><!--判斷招錄小批次當前進度的人員是否全部處理了-->
<mvc:exclude-mapping path="/back/upload"/><!--富文本編輯器圖片上傳-->
<bean class="com.greathack.homlin.interceptor.PermissionInterceptor"></bean>
         
     </mvc:interceptor>
 </mvc:interceptors>   

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM