前端使用富文本编辑器编辑的内容,其中包括图片、附件、视频等文件,想要把文件复制到另一个文件夹。
以如下为例
1.pom.xml中需要导入jsoup的包
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.10.2</version>
</dependency>
2.测试html字符串如下
String dailyNewsContent = “<p>测试1<br/></p><p>
<img src="http://localhost:8490/crm-prodf//ueditor/jsp/upload/image/20200630/1593486817995080146.png" title="1593486817995080146.png"/></p>
<p><img src="http://localhost:8490/crm-prodf//ueditor/jsp/upload/image/20200630/1593486818033075836.png"
title="1593486818033075836.png"/></p><p>测试2</p>”
3.开始
private void saveUeditorFile(String dailyNewsContent) throws IOException{
String fileType = “img ”;
Document doc = Jsoup.parse(dailyNewsContent);
if(doc.select(type).size() >0){
Iterator<Element> iterator = doc.select(type).iterator();
while(iterator.hasNext()){
Element img = iterator.next();
//获取 到文件地址和名称
String src = img.attr("src");
String title = img.attr("title");
//当前服务器实际url
String serverPath = System.getProperty("user.dir");
//拼接文件实际存放的url
String pathA = serverPath.substring(0, serverPath.length()-3);
int a = src.indexOf("ueditor");
String pathC = src.substring(a,src.length());
String pathB = "standalone/deployments/crm-prod-ear.ear/crm-prod-plf.war/";
String path = pathA+pathB+pathC;
//目标url
String savePath = "D:/server/";
//复制文件
File newFile = new File(savePath, title);
BufferedInputStream buffereInput = new BufferedInputStream(new FileInputStream(path));
BufferedOutputStream buffereOutput = new BufferedOutputStream(new FileOutputStream(newFile));
byte[] bytes = new byte[8192];
int n = -1;
while((n = buffereInput.read(bytes,0,bytes.length)) != -1){
buffereOutput.write(bytes,0,n);
}
buffereOutput.flush();// 清空缓冲区
buffereOutput.close();// 关闭输出流
buffereInput.close();
}
}
}