**jsp页面**
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<%@ page import="com.itss.huao.xz.newRecruit.enums.UploadTypeE" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<!DOCTYPE html>
<html>
<head>
<title>上传简历</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<link rel="stylesheet" href="<%=path%>/webT/bootstrap/css/bootstrap.min.css"/>
<link rel="stylesheet" href="<%=path%>/layout/easyui/themes/zzsc.css" />
<link rel="stylesheet" href="<%=path%>/layout/easyui/themes/detailInfo.css" />
<link rel="stylesheet" href="<%=path%>/layout/datagrid/newRecruit/css/importResume.css" />
<script type="text/javascript" src="<%=path%>/webT/bootstrap/js/jquery-1.12.2.js"></script>
<script type="text/javascript" src="<%=path%>/webT/bootstrap/js/bootstrap.js"></script>
<script type="text/javascript" src="<%=path%>/webT/bootstrap/js/layer/layer.js"></script>
<script type="text/javascript">
var selectType = "<%=UploadTypeE.SELECT.getCode()%>";
var dragType = "<%=UploadTypeE.DRAG.getCode()%>";
</script>
</head>
<body>
<div class="container">
<div class="page-header row" >
<h3>上传简历</h3>
</div>
<form id="fileForm" action="fileResume.do?method=uploadResumeFile" role="form" enctype="multipart/form-data" method="post">
<%-- <input type="hidden" name="filePath" value="${filePath}">
<input type="hidden" name="fileName" id="fileName"/>
<input type="hidden" name="token" value ="<%=session.getAttribute( "token" ) %>"> --%>
<div class="selectDom" style="margin:20px 0px 20px 0px;">
<div class="row form-group">
<label class="col-md-2 control-label">
<em class="em-mustin">*</em>
选择职位
</label>
<div class="col-md-5">
<input type="text" id="position" name="position" class="form-control" placeholder="请输入职位……" style="width:80%;" transparent autofocus x-webkit-speech>
</div>
</div>
<div class="upload-body" style="margin-top:42px;">
<div class="upload-pick file-error">
<div class="pick-btn-area">
<div class="pick-remind" style="text-align:center;margin-top:55px;">
<a id="btnUploadOnClick" class="btn btn-primary" style="width:100px;" >请选择文件</a>
<p style="text-align:center;margin-top:15px;">支持PDF、DOX、DOCX格式的简历。</p>
<p>一次最多上传5个。一个简历不超过5M</p>
</div>
</div>
<div class="pick-btn-area" onclick="choosefile()">
<div class="fileBox">
<span id="fileSpan" class="vm" style="font-size:16px">
<img src="/xzgl/layout/easyui/image/file_dnd.png" width="60" height="60">
</img>
或者将文件拖到此处
</span>
<input type="file" id="btnUploadOnClick" style="display:none;" multiple="multiple" />
<ul id="fileList"></ul>
</div>
</div>
</div>
</div>
</div>
<div align="center" style="margin-top:40px;" >
<div class="row" id="selectfile" >
<table class="table table-striped">
<tbody id="tbody-uploadFile">
<tr id="nullFileTr">
<td>目前无上传文件,请选择文件</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="col-md-12" align="center" style="margin:40px 0 40px 0;">
<div class="col-md-12" style="margin:10px 0 20px 0;">
<span class="text-warning warningSpan" style="font-size:11px;"></span>
</div>
<a onclick="javascript:formSubmit()" id="btnSubmit" class="btn btn-primary disabled" style="width:100px;">提交</a>
<a onclick="javascript:history.back(-1)" class="btn btn-default" style="width:100px;margin-left:20px;">取消</a>
</div>
</form>
</div>
<script type="text/javascript" src="<%=path%>/layout/datagrid/newRecruit/js/importResume.js"></script>
<script type="text/javascript" src="<%=path%>/layout/datagrid/newRecruit/js/dragFile.js"></script>
</body>
</html>
css
@CHARSET "UTF-8";
.control-label {
font-size: 15px;
text-align: right;
color: #787878;
font-weight: normal;
padding-top: 4.5px;
}
.row-field {
margin-top: 15px;
margin-bottom: 15px;
}
.page-header {
height: 100px;
text-align: center;
}
.em-mustin {
color: #F72143;
}
#selectfile {
text-align: center;
width: 80%;
}
.removeFile {
color: #D9544F;
cursor: pointer;
padding-left: 20px;
font-size: 20px;
}
#tbody-uploadFile {
font-size: 16px;
}
.title {
text-align: center;
margin-top: 50px;
}
.demo {
width: 900px;
height: 140px;
margin: 50px auto;
}
.drag-area {
width: 100%;
height: 100px;
line-height: 100px;
font-size: 36px;
font-weight: 700;
}
.preview div {
width: 195px;
overflow: hidden;
border: 1px dashed silver;
margin-top: 10px;
float: left;
padding: 9px;
text-align: center;
height: 168px;
}
body {
color: #555;
font-family: HanHei SC, PingFang SC, Microsoft YaHei;
font-size: 14px;
direction: ltr;
-webkit-text-size-adjust: 100%;
-ms-text-size-adjust: 100%;
}
.upload-body {
border: 2px dashed #d5d5d5;
padding: 20px 0;
background-color: #fafbff;
height: 300px;
width: 100%;
box-sizing: border-box;
}
.pick-area {
width: 50%;
height: 260px;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
border-right: 1px solid #d5d5d5;
float: left;
text-align: center;
}
.pick-btn-area {
width: 50%;
height: 260px;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
border-right: 1px solid #d5d5d5;
float: left;
text-align: center;
}
.fileBox {
margin: 50px;
}
.fileInputP {
display: inline-block;
width: 200px;
height: 30px;
border-radius: 5px;
overflow: hidden;
position: relative;
}
.fileInputP i {
display: inline-block;
width: 200px;
height: 30px;
color: #fff;
background: #7d8f33;
text-align: center;
line-height: 30px;
}
#fileInput {
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
opacity: 0;
}
#fileSpan {
display: inline-block;
width: 350px;
height: 150px;
/* border: 2px dashed #ccc; */
text-align: center;
line-height: 150px;
}
.fileList_parent {
margin: 50px;
display: none;
}
.fileList_parent th {
background: #dadada;
font-weight: bold;
}
.fileList_parent th, .fileList_parent td {
padding: 5px;
}
.fileList tr:nth-of-type(2n) {
background: #dadada;
}
.progressParent {
width: 200px;
height: 20px;
border-radius: 5px;
background: #ccc;
overflow: hidden;
position: relative;
}
.progress {
width: 0%;
height: 20px;
background: #7d8f33;
}
.progressNum {
display: inline-block;
width: 100%;
height: 20px;
text-align: center;
line-height: 20px;
color: #fff;
position: absolute;
left: 0;
top: 0;
}
#fileBtn {
margin-left: 50px;
display: none;
}
js 拖拽上传
/**
*/
window.onload = function(){
var uuz = document.getElementById('fileSpan');
uuz.ondragenter = function(e){
e.preventDefault();
}
uuz.ondragover = function(e){
e.preventDefault();
/* this.innerHTML = '请松开';
*/ }
uuz.ondragleave = function(e){
e.preventDefault();
// this.innerHTML = '请拖入要上传的文件';
}
uuz.ondrop = function(e){
e.preventDefault();
var upfile = e.dataTransfer.files[0]; //获取要上传的文件对象(可以上传多个)
var formdata = new FormData();
var xhr = new XMLHttpRequest();
formdata.append('upfile', upfile); //设置服务器端接收的name为upfile
xhr.open("post","fileResume.do?method=uploadResumeFile&uploadType="+dragType);
xhr.onreadystatechange = function(){
if(this.readyState==4){
if(this.status==200){ //上传成功
var resultText = this.responseText;
console.info(resultText);
//转json
var jsonObj = JSON.parse(resultText);
console.info(jsonObj);
if(jsonObj.success){
//生成input表单
var fileId = createInput(jsonObj.uuid);
//生成显示名称
appendFile1(fileId,upfile.name);
}
}else{
alert('上传失败,请使用另一种方式上传');
}
}
}
xhr.send(formdata);
}
}
var fileNum;
function createInput(uuid) {
//获取当前file的数量
fileNum = $(".selectFile").length + 1;
//fileId
var fileId = 'selectFile' + fileNum;
//生成file
var fileDom = '<input type="hidden" id="'+fileId+ '" class="selectFile" name="' + fileId+ '" value="'+uuid+'">';
//添加file元素
$("#selectfile").append(fileDom);
return fileId;
}
function appendFile1(fileId,fileName) {
//去除提交按钮的禁用
$("#btnSubmit").removeClass("disabled");
$("#nullFileTr").hide();
$("#tbody-uploadFile").append(
'<tr class="'+ fileId+ '"><td style="text-align:left;">'+ fileName
+ '<span class="removeFile glyphicon glyphicon-remove-circle" ></span></td></tr>');
}
js上传
/**
*
*/
//div点击div显示 文件选择框
function choosefile() {
var f = document.getElementById(“btnUploadOnClick”);
f.click();
}
//通过文件名,返回文件的后缀名
function fileType(name) {
var nameArr = name.split(“.”);
return nameArr[nameArr.length - 1].toLowerCase();
}
//取文件全名名称
function GetFileName(filepath) {
if (filepath != “”) {
var names = filepath.split(“\”);
return names[names.length - 1];
}
}
function checkFile(fileId) {
//获取文件的名称
var filepath = (“#” + fileId).val();
var fileName = GetFileName(filepath);
var pattern = new RegExp(
“[`~!@#^&()=|{}’:;’,
if (pattern.test(fileName)) {
layer.msg(“文件名只能包含数字、字母、汉字和下划线。”, {
icon : 5,
time : 7000
});
return false;
}
//文件的格式
var type = (fileName.substring(fileName.lastIndexOf(“.”) + 1,
fileName.length)).toLowerCase();
//获取文件的属性
var a = $(“#” + fileId);
if (a[0].size > 4 * 1024 * 1024) {
//文件大小的判断
layer.msg(“文件过大”);
return false;
} else {
if ((type == “doc”) || (type == “docx”) || (type == “pdf”)) {
return true;
} else {
layer.msg(“该格式不支持上传”);
return false;
}
}
}
function appendFile(fileId) {
if (checkFile(fileId)) {
//去除提交按钮的禁用
(“#btnSubmit”).removeClass(“disabled”);(“#nullFileTr”).hide();
//获取文件的名称
var fileName = (“#” + fileId).val();
var pos = fileName.lastIndexOf(“\”);
fileName = fileName.substring(pos + 1);(“#tbody-uploadFile”)
.append(
‘
action 后台
/**
* 上传文件 @Title: uploadResumeFile @Description:
* TODO(这里用一句话描述这个方法的作用) @param: @param mapping @param: @param
* arg1 @param: @param request @param: @param
* response @param: @return @author LiYonghui @date 2017年8月1日
* 下午4:46:48 @return: ActionForward @throws
*/
public ActionForward uploadResumeFile(ActionMapping mapping, ActionForm arg1, HttpServletRequest request, HttpServletResponse response) {
response.setContentType("text/html;charset=UTF-8");
boolean success = false;
String msg = "上传失败";
//记录上传的uuid;
String uploadUUID = "";
try {
request.setCharacterEncoding("UTF-8");
String position = request.getParameter("position"); //职务
if(position==null){
position="";
}
//上传方式类型
String uploadType = request.getParameter("uploadType");
if(uploadType==null || uploadType.equals("")){
uploadType=UploadTypeE.SELECT.getCode();
}
MultipartRequestHandler handler = arg1.getMultipartRequestHandler();
@SuppressWarnings("unchecked")
Hashtable<Object, FormFile> fileMap = handler.getFileElements();
// 遍历文件列表
for (Object key : fileMap.keySet()) {
List<String> imgList = new ArrayList<String>();
FormFile formFile = fileMap.get(key);
// 随机name,防止重复提交
String fileName = formFile.getFileName();
// 文件全路径+name
fileName = resetFile(fileName);
// 拼接路径
String fillFullPathName = request.getSession().getServletContext().getRealPath("/") + RESUME_FILPATH+ "/" + fileName;
String resumeUploadBootPath = request.getSession().getServletContext().getRealPath("/") + PDF_FILPATH;
String newWordPath= request.getSession().getServletContext().getRealPath("/") + WORD_FILEPATH;
String pdfImgPath = request.getSession().getServletContext().getRealPath("/") + PDF_IMG;
success = doUploadFile(formFile, fillFullPathName, fileName);
if (success) {
//上传pdf
boolean isCreatePdf = isCreatePdf(fileName);
boolean pdfExsit = false;
if(isCreatePdf){
//word转pdf
pdfExsit = createPdf(fileName, resumeUploadBootPath, fillFullPathName);
int beginIndex = fileName.lastIndexOf(".");
String pdfName = fileName.substring(0,beginIndex);
resumeUploadBootPath+="/"+pdfName+".pdf";
}else{
//上传pdf
pdfExsit = true;
resumeUploadBootPath = fillFullPathName;
}
if(pdfExsit){
PDFToImage pDFToImage = new PDFToImage();
imgList = pDFToImage.pdftoIamge(1.0f, resumeUploadBootPath, pdfImgPath);
}
//检索文件信息,返回简历的主键
//检索 word
if (isCreatePdf) {
String uuid = generateResumeFields(fillFullPathName,position,newWordPath,uploadType);
if(uuid!=null){
//保存状态
saveRcruitmentStatus(uuid);
//保存图片
saveImg(imgList, uuid);
uploadUUID = uuid;
}
}else{//检索pdf
String uuid = generateResumePdf(resumeUploadBootPath,position);
if(uuid!=null){
//保存状态
saveRcruitmentStatus(uuid);
//保存图片
saveImg(imgList, uuid);
}
}
msg = "上传成功";
}
}
//获取拖拽uuid
@SuppressWarnings("unchecked")
//查询uuid是否存在
Hashtable<String, Object> textElements = handler.getTextElements();
for (String key : textElements.keySet()) {
if(key.startsWith("selectFile")){
String uuid = ((String[])textElements.get(key))[0];
//查询uuid是否存在,如果存在,更改为激活状态(1),position
boolean isExsit = ImportResumeDao.findAnswerByPIdAndType(uuid);
if (isExsit) {
String state = YesOrNoE.YES.getCode();
ImportResumeDao.updateResumeState(uuid,state,position);
}
}
}
if(uploadType.equals(UploadTypeE.DRAG.getCode())){
//如果是拖拽方式,返回参数
Map<String,String> map = new HashMap<String, String>();
map.put("uuid", uploadUUID);
map.put("success",success+"");
map.put("msg", msg);
JsonUtil.writeToResponse(map, response);
return null;
}
} catch (Exception e) {
success = false;
msg = "上传失败";
e.printStackTrace();
}
//刷新页面
refresh(request);
request.setAttribute("msg", msg);
request.setAttribute("success", success);
return mapping.findForward("importResumes");
}
/**
* 读取pdf
* @param pdfFilePath
* @return
*/
public static String getTextFromPDF(String pdfFilePath)
{
String result = null;
FileInputStream is = null;
PDDocument document = null;
try {
is = new FileInputStream(pdfFilePath);
PDFParser parser = new PDFParser(is);
parser.parse();
document = parser.getPDDocument();
PDFTextStripper stripper = new PDFTextStripper();
result = stripper.getText(document);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (document != null) {
try {
document.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
/**
* 检索pdf
* @param pdfPath
* @return
*/
@SuppressWarnings("static-access")
public static String generateResumePdf(String pdfPath,String position) {
//简历的主键
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
try {
RecruitUserInfo recruit = new RecruitUserInfo();
GenerateFile generateFile = new GenerateDoc();
// 获取文本
String text = getTextFromPDF(pdfPath);
System.out.println(text);
// 初始化文本,去除特殊字符
text = generateFile.initText(text);
System.out.println(text);
// 获取分类信息;姓名、性别、邮箱等
SearchCategoryE[] categorys = SearchCategoryE.values();
// 获取实体类属性集合
Field[] fields = generateFile.getClassFields(recruit);
recruit = generateFile.getInitObject(fields, categorys, text);
recruit.setId(uuid);
Date now = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");//可以方便地修改日期格式
String time = dateFormat.format( now );
recruit.setLeadInTime(time);
recruit.setPosition(position);
ImportResumeDao resumeDao = new ImportResumeDao();
int count = resumeDao.saveResume(recruit);
if(count<=0){
uuid = null;
}
} catch (Exception e) {
e.printStackTrace();
}
return uuid;
}
/**
* word生成pdf
* @param fileName
* @param resumeUploadBootPath
* @param fillFullPathName
* @return
*/
private boolean createPdf(String fileName,String resumeUploadBootPath,String fillFullPathName){
//截取文件的名称,不要后缀
int beginIndex = fileName.lastIndexOf(".");
String pdfName = fileName.substring(0,beginIndex);
resumeUploadBootPath+="/"+pdfName+".pdf";
//生成doc2pdf
boolean pdfsuccess = doc2pdf(fillFullPathName,resumeUploadBootPath);
return pdfsuccess;
}
/**
* 上传pdf
* @param fileName
* @return
*/
private boolean isCreatePdf(String fileName){
boolean success = true;
//截取文件的名称,不要后缀
int beginIndex = fileName.lastIndexOf(".");
String fuxx = fileName.substring(beginIndex+1);
if(fuxx.equals("pdf")){
success = false;
}
return success;
}
/**
* 上传
*/
public boolean doUploadFile(FormFile formFile, String fillFullPathName, String fileName) throws Exception {
boolean success = false;
// 先将上传的文件读进来。
InputStream is = formFile.getInputStream();
byte[] arr = new byte[is.available()];
is.read(arr);
OutputStream os = new FileOutputStream(fillFullPathName);
os.write(arr);
os.flush();
os.close();
is.close();
success = true;
return success;
}
/**
*
*
* @throws Exception
* @Title: createImg @Description: TODO(这里用一句话描述这个方法的作用) @param: @param
* fillFullPath @param: @param
* resumeUploadBootPath @param: @return @author LiYonghui @date
* 2017年8月2日 上午11:22:09 @return: boolean @throws
*/
public boolean doc2pdf(String fillFullPath,String resumeUploadBootPath){
boolean pdfsuccess = true;
try{
// word 转 pdf
//OfficeToPDF wordToPDF = new OfficeToPDF();
// 空pdf文件
//String emptyPDFFile = resumeUploadBootPath + "emptyPDF.pdf";
String emptyPDFFile =GeneratePDF.writeSimplePdf(resumeUploadBootPath);
//wordToPDF.docToPdf(new File(fillFullPath), new File(emptyPDFFile)); //报错
Office2PdfUtil office2PdfUtil= Office2PdfUtil.getOffice2PdfUtil();
office2PdfUtil.office2Pdf(fillFullPath, emptyPDFFile);
}catch (Exception e) {
pdfsuccess = false;
e.printStackTrace();
}
return pdfsuccess;
}
/**
* 检索对应的字段 @Title: generateResumeFields @Description:
* TODO(这里用一句话描述这个方法的作用) @param: @param fillFullPath @param: @param
* resumeUploadBootPath @param: @return @author LiYonghui @date 2017年8月2日
* 上午11:21:39 @return: boolean @throws
*/
@SuppressWarnings("static-access")
public static String generateResumeFields(String fillFullPath,String position,String newWordPath,String uploadType) {
//简历的主键
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
try {
RecruitUserInfo recruit = new RecruitUserInfo();
GenerateFile generateFile = new GenerateDoc();
// 获取文本
String text = generateFile.getText(fillFullPath,newWordPath);
// 初始化文本,去除特殊字符
text = generateFile.initText(text);
// 获取分类信息;姓名、性别、邮箱等
SearchCategoryE[] categorys = SearchCategoryE.values();
// 获取实体类属性集合
Field[] fields = generateFile.getClassFields(recruit);
recruit = generateFile.getInitObject(fields, categorys, text);
recruit.setId(uuid);
recruit.setPosition(position);
recruit.setType(uploadType);
if(uploadType.equals(UploadTypeE.DRAG.getCode())){
recruit.setState(YesOrNoE.NO.getCode());
}else{
recruit.setState(YesOrNoE.YES.getCode());
}
Date now = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");//可以方便地修改日期格式
String time = dateFormat.format( now );
recruit.setLeadInTime(time);
ImportResumeDao resumeDao = new ImportResumeDao();
int count = resumeDao.saveResume(recruit);
if(count<=0){
uuid = null;
}
} catch (Exception e) {
e.printStackTrace();
}
return uuid;
}
/**
* 保存简历状态
* @Title: saveRcruitmentStatus
* @Description: TODO(这里用一句话描述这个方法的作用)
* @param: @param uuid 简历的主键
* @author LiYonghui
* @date 2017年8月8日 下午5:36:15
* @return: void
* @throws
*/
private void saveRcruitmentStatus(String uuid){
RcruitmentStatus status = new RcruitmentStatus();
String id = UUID.randomUUID().toString().replaceAll("-", "");
status.setId(id);
resumeDao.insertStatus(status, uuid);
}
/**
* 保存图片
* @Title: saveImg
* @Description: TODO(这里用一句话描述这个方法的作用)
* @param: @param imgList
* @param: @param uuid 简历的主键
* @author LiYonghui
* @date 2017年8月8日 下午5:36:44
* @return: void
* @throws
*/
private void saveImg(List<String> imgList,String uuid){
UploadRsumePath img = new UploadRsumePath();
String imgpath = "";
if (imgList != null) {
for (int i = 0; i < imgList.size(); i++) {
String s = (String) imgList.get(i);
imgpath += "," + (PDF_IMG + s.substring(s.lastIndexOf("/")+1));
}
}
if (!imgpath.equals("")) {
imgpath = imgpath.substring(1);
}
img.setImgpath(imgpath);
String id = UUID.randomUUID().toString().replaceAll("-", "");
img.setId(id);
resumeDao.insertImage(img, uuid);
}
/**
* 重命名文件
*
* @param oldName
* @return
*/
private String resetFile(String oldName) {
// 生成一个随机数
String newName = UUID.randomUUID().toString();
int beginIndex = oldName.lastIndexOf(".");
newName += oldName.substring(beginIndex);
return newName;
}