springmvc框架搭建及详解_java+Spring+Ueditor实现图片上传功能

更新时间:2020-10-09    来源:php入门    手机版     字体:

【www.bbyears.com--php入门】

公司用的是阿里云的图片服务器,需要直接把文章中图片上传到服务器上,但是这个编辑器的上传图片是直接上传到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 = $(""),
                var $img = $(""),
                    $item = $("").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();
        }

本文来源:http://www.bbyears.com/jiaocheng/103550.html