java文件上传+预览
form表单上传文件
controller接受文件将路径保存到数据库
预览文档查询数据库信息并转为pdf进行预览
h5显示预览的文件
form表单上传文件
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<link rel="stylesheet" href="引入所需的css文件的路径"/>
<script type="text/javascript" src="引入js文件的路径"></script>
</head>
<body>
<form id="form" name="form" class="" method="post" action="(后台方法路径)*/*"
enctype="multipart/form-data">
上传文件:
<input class="id-input-file-2" type="file" name="wordFile" id="wordFile">
<button id="submitBtn" type="button" >提交</button>
</form><script type="text/javascript">
jQuery(function ($) {
$('#submitBtn').click("click", function () {
var $form = $("#form");
var $submitBtn = $("#submitBtn");
$("#form").attr("action", "(后台方法路径对应form表单中的action)*/*/uploadFile.json")
$("#form").ajaxSubmit({
dataType: "json",
beforeSubmit: function(){
$submitBtn.prop("disabled", true);
},
success: function (data) {
//设置返回信息验证是否上传成功
if (data.status == '0') {
$submitBtn.attr("disabled",true);
layer.alert('上传成功!')
}
},
error: function (xhr, textStatus, errorThrown) {
layer.alert("系统未知错误");
}
});
})
});
</script>
</body>
</html>controller接受文件将路径保存到数据库
/**
*
**/
@ResponseBody
@RequestMapping(value = "/uploadFile", produces = "application/json; charset=utf-8")
public ResponseEntity<ResponseDto> fileUpload(HttpServletRequest request,MultipartFile wordFile) {
//上传文件的方法
String url=getFileByMultipartFile(wordFile);
//将文件路径保存到数据库
int i=noticeService.fileUpload(url);
if(i>0){
return "返回给success的信息:上传成功";
}
return "上传失败";
}
public static String getFileByMultipartFile(MultipartFile mFile) {
if(mFile.getSize()<1){
return null;
}
//获取文件名
String orgFileName = mFile.getOriginalFilename();
//获取String类型的时间字符串,方法自己研究,代码不在展出
String dateTimeStr = DateUtil.dateFormat(new Date(), "yyyyMMddHHmmss");
StringBuilder path = new StringBuilder("存放文件的服务器路径");
path.append(dateTimeStr).append(orgFileName);
//文件名称+路径
String fileFullPath = path.toString(); //将文件保存到本地路径
StringBuilder fileName=new StringBuilder("存放文件到本地路径");
fileName.append(dateTimeStr).append(orgFileName);
//保存文件
File file1 = new File(fileName.toString());
File file = new File(fileFullPath);
if(!file.exists()||!file1.exists()){
try {
FilesUtil.createDirectoryAndFile(file);
FilesUtil.createDirectoryAndFile(file1);
mFile.transferTo(file);
mFile.transferTo(file1);
} catch (IOException e) {
e.printStackTrace();
}
}
//返回文件名称
return file1.getName();
}
/**
* 创建文件夹和文件 例如:C:/aaa/bbb/ccc.txt,若此路径存在则创建ccc.txt<br>
* 若此路径不存在则先创建文件夹再创建文件。<br>
* @param file
* @throws IOException
*/
public static boolean createDirectoryAndFile(File file) throws IOException {
String path = file.getPath();
String name = file.getName();
if(name.indexOf(".") > -1){
String directoryStr = path.substring(0, path.length()-name.length());
File directory = new File(directoryStr);
if(!directory.exists()){
if(directory.mkdirs() && FilesUtil.createFile(file)){
return true;
}
}
}
return false;
}
预览文档查询数据库信息并转为pdf进行预览
/**
* 把信息放到jsp展示,
*/
@RequestMapping("/preview")
public ModelAndView preview(HttpServletRequest request) {
//查询数据库获取文件信息
//根据自己需求来定义查询方法这里是简单的查询
//TabCoreNoticeEntity coreNoticeEntity = noticeService.select(); 查询在实体类中的全部信息,包括文件名
String fileUrl=service.selectUrl();
String inPath ="文件所在的本地路径" + fileUrl;
System.out.println(inPath);
//将文件转为pdf,并返回pdf的路径
//word转为pdf进行预览
String outPath ="文件输出位置,用户可以访问到的路径:例如:webapp下的file文件夹";
try {
Word2PdfUtil.word2pdf(inPath, outPath);
} catch (Exception e) {
e.printStackTrace();
}
//去掉文件的后缀名
String name=fileUrl.substring(0,fileUrl.lastIndexOf("."));
//把文件改为pdf格式
String realPdfUrl=name+".pdf";
//修改此地址:上线时在配置文件中修改为服务器地址
String pdfFileName=WEB_DOMAIN+"/img/"+realPdfUrl;
System.out.println(pdfFileName);
modelAndView.addObject("url",pdfFileName);
modelAndView.setViewName("要返回的页面");
return modelAndView;
}
import java.io.*;/**
* word2pdf
* @author zhaolw
* @version 1.0
* @date 2018/10/9 10:28
* @since 1.0
*/
public class Word2PdfUtil {
private static final String OFFICE_PATH = "安装libreoffice的路径 :一般为:C:\\Program Files\\LibreOffice\\program";
public static void word2pdf(String inFullPath, String outPath) throws Exception {
if (!new File(inFullPath).exists()) {
throw new FileNotFoundException();
}
String command = String.format("%s/soffice --convert-to pdf:writer_pdf_Export %s --outdir %s", OFFICE_PATH, inFullPath, outPath);
String output = executeCommand(command);
} protected static String executeCommand(String command) throws IOException, InterruptedException {
StringBuffer output = new StringBuffer();
Process p;
p = Runtime.getRuntime().exec(command);
p.waitFor();
try (
InputStreamReader inputStreamReader = new InputStreamReader(p.getInputStream(), "UTF-8");
BufferedReader reader = new BufferedReader(inputStreamReader)
) {
String line = "";
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}
}
p.destroy();
return output.toString();
}
}
h5显示预览的文件
<!DOCTYPE html>
<html>
<head>
</head><body>
<embed width="100%" height="500px" name="plugin" id="plugin" src="${url}"
type="application/pdf" internalinstanceid="5" /></body>
</html>
至此,最简单的文件上传后的预览显示不出意外是可以实现的。