您的位置:首页 > 编程语言 > Java开发

UMeditor与SpringMVC的整合和上传图片使用

2017-08-31 18:41 369 查看
在一次项目中使用了百度的富文本编辑器UMeditor,发现官方的Demo中,是用jsp写的
而在SpringMVC中无法访问jsp路径。于是进行了小的改造一下。

UMeditor版本为Mini版的1.2.3-JSP版

1.首先把官方的几个文件添加进项目依赖。



两个jar包放到项目的lib文件夹,并添加Build Path依赖项

如果是maven项目,直接添加pom.xml中的配置即可。

2.然后把Uploader.java复制到项目中来。

3.参照原始的imageUp.jsp的内容,在Controller里面添加一个图片上传的函数。
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ page import="com.baidu.ueditor.um.Uploader" %>

<%
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
Uploader up = new Uploader(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>");
}
%>


以上为原始的官方imageUp.jsp内容,参照编写的Controller如下

@ResponseBody
@RequestMapping("imageUp")
public String imageUp(MultipartFile upfile,HttpServletRequest request, HttpServletResponse response, org.springframework.ui.Model modelMap) {

Uploader up = new Uploader(request);
up.setSavePath("upload");
String[] fileType = {".gif" , ".png" , ".jpg" , ".jpeg" , ".bmp"};
up.setAllowFiles(fileType);
up.setMaxSize(10000); //单位KB
try {
up.upload(upfile);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

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


默认从request里面好像得不到上传的图片数据,于是添加了个参数upfile,这个参数要和umeditor.config.js中配置的imageFieldName要一致。

4.在Uploader.java文件里添加了一个重载的函数。带参数的upload函数。
完整的代码如下

package com.baidu.ueditor.um;

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.springframework.web.multipart.MultipartFile;
import org.apache.commons.fileupload.servlet.*;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;

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 = "fileUpload";
// 文件允许格式
private String[] allowFiles = { ".rar", ".doc", ".docx", ".zip", ".pdf",".txt", ".swf", ".wmv", ".gif", ".png", ".jpg", ".jpeg", ".bmp" };
// 文件大小限制,单位KB
private int maxSize = 10000;

privat
b26e
e 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", "未知错误");

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

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


5.以上都修改完毕后,修改umeditor.config.js配置文件

imageUrl为Controller的地址,imagePath暂时留空,第三个不变。

修改完成后,就可以正常的上传图片显示了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐