好友
阅读权限10
听众
最后登录1970-1-1
|
UEditor富文本内容保存或下载成word文档
首先感谢该博主的文章:link
- UEditor官网下载:完整源码,JSP版本
- 创建springboot项目
①将完整源码中的/jsp/src目录下的文件夹拷贝至项目的src目录下;
②将JSP版本下的所有文件拷贝至项目的resources/static下;
③将JSP版本下的jsp/config.json文件拷贝至resources目录;
④将JSP版本下的index.html拷贝到resources/templates下,并修改该页面所引用的css/js路径;
-
引用依赖
<properties>
<java.version>1.8</java.version>
<poi.version>3.17</poi.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<!-- 热部署 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
<scope>true</scope>
</dependency>
<!-- JSON-->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20160810</version>
</dependency>
<!-- 上传控件 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.11</version>
</dependency>
<!-- poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>${poi.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>${poi.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>${poi.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>${poi.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>ooxml-schemas</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.7</version>
</dependency>
<dependency>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>xdocreport</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
- 编辑application.yml文件
server:
port: 8890
#上传图片大小设置
max-http-header-size: 102400
#文件上传保存的路径
web:
file-path: E:\Example
spring:
mvc:
static-path-pattern: /**
resources:
static-locations: classpath:/META-INF/resources/, classpath:/resources/, classpath:/static/, classpath:/public/, file:${web.file-path}
- 修改resources/config.json文件
// 增加代码,表示上传路径
"basePath": "E:/Example/"
// 将
"imagePathFormat": "/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}",
// 修改为下面这行,这是上传的图片所保存的目录
"imagePathFormat": "/upload/{time}{rand:6}",
- 修改resources/static/ueditor/ueditor.config.js文件
serverUrl: URL + "jsp/controller.jsp"
// 修改为
serverUrl: "/config"
- 编写控制器
// 页面显示
@RequestMapping("/")
public String index() {
return "index";
}
// 映射config.json
@RequestMapping("/config")
public void config(HttpServletRequest request, HttpServletResponse response) {
response.setContentType("application/json");
String rootPath = request.getSession().getServletContext().getRealPath("/");
System.out.println(rootPath);
try {
String exec = new ActionEnter(request, rootPath).exec();
PrintWriter writer = response.getWriter();
writer.write(exec);
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
-
修改UEditor相关源码文件
// **修改ConfigManeger类的getConfigPath()方法:
private String getConfigPath () {
// return this.parentPath + File.separator + ConfigManager.configFileName;
// ————————————替换修改
try{
//获取classpath下的config.json路径
return this.getClass().getClassLoader().getResource("config.json").toURI().getPath();
}catch (URISyntaxException e){
return null;
}
// ————————————————————————
}
// **修改ConfigManager类的getConfig()方法:
// ————————增加的代码————————
conf.put( "basePath", this.jsonConfig.getString("basePath") );
// ————————————————————————
conf.put( "savePath", savePath );
conf.put( "rootPath", this.rootPath );
// **修改BinaryUploader类**
// 注释该代码:
FileItemStream fileStream = null;
boolean isAjaxUpload = request.getHeader( "X_Requested_With" ) != null;
// 注释该代码:
ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
if ( isAjaxUpload ) {
upload.setHeaderEncoding( "UTF-8" );
}
// 注释该代码:
FileItemIterator iterator = upload.getItemIterator(request);
while (iterator.hasNext()) {
fileStream = iterator.next();
if (!fileStream.isFormField())
break;
fileStream = null;
}
if (fileStream == null) {
return new BaseState(false, AppInfo.NOTFOUND_UPLOAD_DATA);
}
// 将
String originFileName = fileStream.getName();
// 修改为:
String originFileName = multipartFile.getOriginalFilename();
// 将
String physicalPath = (String) conf.get("rootPath") + savePath;
// 修改为:
String basePath = (String) conf.get("basePath");
String physicalPath = basePath + savePath;
// 将
InputStream is = fileStream.openStream();
// 修改为:
InputStream is = multipartFile.getInputStream();
- 编写ConfigUtils工具,意在获取路径
// 获取config.json文件中的image的上传路径
public static String imagePath() {
ClassPathResource config = new ClassPathResource("config.json");
try {
File file = config.getFile();
String input = FileUtils.readFileToString(file, "UTF-8");
JSONObject jsonObject = JSONObject.fromObject(input);
if (jsonObject != null) {
return jsonObject.get("imagePathFormat").toString();
}
} catch (Exception e) {
e.getStackTrace();
}
return null;
}
// 获取yml中自定义上传的根路径,届时将跟image路径替换拼接起来,word中的图片才能显示。
public static String filePath() {
YamlPropertiesFactoryBean yamlMapFactoryBean = new YamlPropertiesFactoryBean();
yamlMapFactoryBean.setResources(new ClassPathResource("application.yml"));
Properties properties = yamlMapFactoryBean.getObject();
assert properties != null;
return properties.getProperty("web.file-path");
}
- 编写POIUtils工具,输出保存word
/**
* 在Config.js中的图片路径,对应替换
*/
private static String IMAGE_PATH = Objects.requireNonNull(ConfigUtils.imagePath()).replace("{time}{rand:6}", ""); // 上传的图片路径
private static String FILE_PATH = ConfigUtils.filePath(); // 上传路径
/**
* ueditor导出word到浏览器下载
*
* home.php?mod=space&uid=952169 request request
* @param response response
* @param content 内容
* @param fileName 文件名
* @param suffix 拓展名
*/
public static void exportWordToBrowser(HttpServletRequest request,
HttpServletResponse response,
String content,
String fileName,
String suffix) {
try {
// 传入的图片路径,未有头路径,需要替换后保存的word才能显示图片。
String str = content.replace(IMAGE_PATH, FILE_PATH.concat(IMAGE_PATH));
StringBuilder sbf = new StringBuilder();
sbf.append("<html><body>"); //缺失的首标签
sbf.append(str); // 富文本内容
sbf.append("</body></html>"); // 缺失的尾标签
byte[] b = sbf.toString().getBytes("GBK"); // 这里是必须要设置编码的,不然导出中文就会乱码。
ByteArrayInputStream bais = new ByteArrayInputStream(b); // 将字节数组包装到流中
POIFSFileSystem poifs = new POIFSFileSystem();
DirectoryEntry directory = poifs.getRoot();
DocumentEntry documentEntry = directory.createDocument("WordDocument", bais); // 该步骤不可省略,否则会出现乱码。
// 输出文件
request.setCharacterEncoding("utf-8");
response.setContentType("application/msword"); // 导出word格式
response.addHeader("Content-Disposition", "attachment;filename=" +
new String(fileName.getBytes("GB2312"), "iso8859-1").concat(".").concat(suffix));
ServletOutputStream sos = response.getOutputStream();
poifs.writeFilesystem(sos);
bais.close();
sos.close();
poifs.close();
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
/**
* ueditor保存word至硬盘
*
* @param content 内容
* @param savePath 保存路径
* @param fileName 完整文件名
*/
public static void exportWordToDisk(String content, String savePath, String fileName) {
try {
// 传入的图片路径,未有头路径,需要替换后保存的word才能显示图片。
String str = content.replace(IMAGE_PATH, FILE_PATH.concat(IMAGE_PATH));
StringBuilder sbf = new StringBuilder();
sbf.append("<html><body>"); //缺失的首标签
sbf.append(str); // 富文本内容
sbf.append("</body></html>"); // 缺失的尾标签
byte[] b = sbf.toString().getBytes("GBK");
ByteArrayInputStream bais = new ByteArrayInputStream(b);
POIFSFileSystem poifs = new POIFSFileSystem();
DirectoryEntry directory = poifs.getRoot();
DocumentEntry documentEntry = directory.createDocument("WordDocument", bais);
if (!new File(savePath).isDirectory())
new File(savePath).mkdir();
FileOutputStream os = new FileOutputStream(savePath.concat(fileName));
// 输出文件
poifs.writeFilesystem(os);
bais.close();
os.close();
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
-
编写控制器方法
/**
* 导出成word浏览器下载
* @param request
* @param response
* @param content
*/
@RequestMapping("/exportWordToBrowser")
public void exportWordToBrowser(HttpServletRequest request, HttpServletResponse response, @RequestParam("content") String content) {
POIUtils.exportWordToBrowser(request, response, content,"demo", "docx");
}
/**
* 导出成word保存到硬盘
* @param content
* @return
*/
@RequestMapping("/exportWordToDisk")
@ResponseBody
public R exportWordToDisk(@RequestParam("content") String content) {
try {
String savePath = ConfigUtils.filePath().concat("/file/");
POIUtils.exportWordToDisk(content, savePath, "save.docx");
return R.ok();
} catch (Exception e) {
return R.error();
}
}
-
修改index.html方法
// 导出word至硬盘
function saveWord() {
$.ajax({
url: '/exportWordToDisk',
data: {
content: UE.getEditor('editor').getContent()
},
headers: {
'Content-Type': 'application/json;charset=utf8'
},
success: function (res) {
if (res.code === 0) {
alert(res.msg)
}
}
})
}
// 导出word至浏览器;使用form表单提交内容更多
function downloadWord() {
var url = "/exportWordToBrowser";
var form = $("<form></form>").attr("action", url).attr("method", "post");
form.append($("<input></input>").attr("type", "hidden").attr("name", "content").attr("value", UE.getEditor('editor').getContent()));
form.appendTo('body').submit().remove();
}
示例
示例
附件:
example.7z
(2.64 MB, 下载次数: 118)
|
|