java+Spring+Ueditor實現圖片上傳功能

來源:互聯網
上載者:User

公司用的是阿里雲的圖片伺服器,需要直接把文章中圖片上傳到伺服器上,但是這個編輯器的上傳圖片是直接上傳到Tomcat的根目錄。

不能滿足要求,嘗試改造了一下上傳圖片的功能。

下載下來的編輯器直接匯入項目webapp目錄下

因為用的是Spring架構,基本已經包含了ueditor需要的幾個jar包,所以不需要匯入了。

需要注意的是,這個ueditor-1.1.1.jar的這個jar包,其實不需要匯入,因為這個包裡面就只有一個檔案Uploader.java

而在ueditor的jsp目錄下已經有了Uploader.java檔案,所以直接把這個檔案copy到工作區中,訪問這個檔案就可以了。

在調用的地方改一下目錄

把

<%@ page import="com.baidu.ueditor.um.Uploader" %>

改成

<%@ page import="com.myproject.upload.Uploader"%>

如下圖:

然後關鍵就是要改造一下Uploader.java這個類。

原有上傳代碼如下:

 代碼如下 複製代碼

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

修改後:

 代碼如下 複製代碼

// 改造後的代碼,百度原有代碼注釋了
    public void upload() throws Exception
    {
        boolean isMultipart = ServletFileUpload.isMultipartContent(this.request);
        if (!isMultipart)
        {
            this.state = this.errorInfo.get("NOFILE");
            return;
        }
        try
        {
            MultipartResolver resolver = new CommonsMultipartResolver(
                    this.request.getSession().getServletContext());
            MultipartHttpServletRequest multipartRequest = resolver.resolveMultipart(request);
            CommonsMultipartFile orginalFile = (CommonsMultipartFile) multipartRequest.getFile("upfile");
            
            this.originalName = orginalFile.getOriginalFilename();
            if (!this.checkFileType(this.originalName))
            {
                this.state = this.errorInfo.get("TYPE");
                return;
            }
            this.type = this.getFileExt(this.originalName);
            this.size = orginalFile.getSize();
            
            // 這裡是公司內部上傳到阿里雲伺服器的工具類
            String key = ImgUtils.uploadImage("xxxx",
                    ImageKind.Picture,
                    orginalFile.getInputStream(),
                    this.size);
            
            this.fileName = key;
            this.url = "http://xxx.aliyuncs.com/" + key;
            this.state = this.errorInfo.get("SUCCESS");
        }
        catch (Exception e)
        {
            this.state = this.errorInfo.get("UNKNOWN");
        }
}

用到了Spring的這兩個檔案

 代碼如下 複製代碼

import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

然後編輯器頁面上顯示的時候,img的src目錄需要改一下

 代碼如下 複製代碼

callback: function (editor, $w, url, state) {
            if (state == "SUCCESS") {
                //顯示圖片計數+1
                Upload.showCount++;
                var $img = $("<img src='" + editor.options.imagePath + url + "' class='edui-image-pic' />"),
                var $img = $("<img src='" + url + "' class='edui-image-pic' />"),
                    $item = $("<div class='edui-image-item edui-image-upload-item'><div class='edui-image-close'></div></div>").append($img);
                if ($(".edui-image-upload2", $w).length < 1) {
                    $(".edui-image-content", $w).append($item);
                    Upload.render(".edui-image-content", 2)
                        .config(".edui-image-upload2");
                } else {
                    $(".edui-image-upload2", $w).before($item).show();
                }
                $img.on("load", function () {
                    Base.scale(this, 120);
                    Base.close($(this));
                    $(".edui-image-content", $w).focus();
                });
            } else {
                currentDialog.showTip( state );
                window.setTimeout( function () {
                    currentDialog.hideTip();
                }, 3000 );
            }
            Upload.toggleMask();
        }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.