web.xml配置
<servlet>
<display-name>InitDataServlet</display-name>
<servlet-name>InitDataServlet</servlet-name>
<servlet-class>com.servlet.InitDataServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>UploadResumeServlet</servlet-name>
<servlet-class>com.upload.servlet.UploadResumeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UploadResumeServlet</servlet-name>
<url-pattern>/UploadResumeServlet</url-pattern>
</servlet-mapping>
config.properties
upload.resume= E:/upload
<td width="100px;"><input type="file" name="uploadify" id="wordUpload"/></td>
<td colspan="2" style="width:400px;">文件名:<div id="fileName" style="width:350px;word-wrap:break-word;"></div></td>
var wordPath="";
//jquery 的上传插件
$("#wordUpload").uploadify({
'onInit': function () {
$("#wordUpload-queue").hide();
},
'fileTypeDesc' : 'Word Files',
swf : '<%=path%>/uploadify/uploadify.swf',
uploader : '<%=path%>/UploadResumeServlet',
buttonText : "浏览",
fileSizeLimit : 0,
'fileTypeExts' : '*.doc; *.docx',
'width' : 80,
'height' : 20,
'multi':true,
'onUploadSuccess' : function(file, data, response) {
if (response) {
data = data.replace(/'/g, "\"");
var json = $.parseJSON(data);
var state = json.state;
if(json.result){
wordPath += json.url + "!,!";
if(state == "SUCCESS"){
var fileName = json.originalName + " , ";
$("#fileName").append(fileName);
}
}else{
$.messager.alert("提示",state,"error");
}
}
}
});
//项目启动加载需要保存的路径
public class InitDataServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public InitDataServlet()
{
super();
}
/**
* @see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException
{
RandomUtil.day = new Date();
Const.UPLOAD_RESUME_URL = PropertyLoader.readConfigProperty("upload.resume");
}
}
//读取配置文件的路径和创建临时文件夹,配置文件放在src下
//通过创建一个java.util.Properties的对象,然后在指定properties文件之后通过FileInputStream读取它,
//将这个InputStream作为参数传给properties对象。properties对象的load方法就把结果解析出来了
public class PropertyLoader
{
private static Map<String, Properties> propertiesMap = new HashMap<String, Properties>();
//加载配置
public static String readConfigProperty(String key)
{
return read("config.properties", key);
}
//读取配置
public static String read(String fileName, String key)
{
if (!propertiesMap.containsKey(fileName) || propertiesMap.get(fileName) == null)
{
loadProperty(fileName);
}
Properties properties = propertiesMap.get(fileName);
return properties.getProperty(key);
}
//根据配置信息
private static void loadProperty(String fileName)
{
Properties properties = new Properties();
try
{
InputStream in = new BufferedInputStream(new FileInputStream(getConfigDirectoryPath() + fileName));
properties.load(in);
propertiesMap.put(fileName, properties);
}
catch (Exception e)
{
e.printStackTrace();
}
}
private static String getConfigDirectoryPath()
{
try
{
String url = URLDecoder.decode(PropertyLoader.class.getProtectionDomain().getCodeSource().getLocation().getFile(), "UTF-8");
url = url.substring(0, url.indexOf("/classes/") + 9);
return url;
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
return null;
}
}
}
//上传文件的servlet
public class UploadResumeServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public UploadResumeServlet()
{
super();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
Uploader up = new Uploader(request);
up.setSavePath(Const.UPLOAD_RESUME_URL);
String[] fileType = { ".doc", ".docx" };
up.setAllowFiles(fileType);
up.setMaxSize(20480); // 单位KB
JSONObject json = new JSONObject();
try
{
up.upload();
json.put("result", true);
json.put("url", up.getFilePath());
json.put("originalName", up.getOriginalName());
}
catch (Exception e)
{
json.put("result", false);
}
json.put("state", up.getState());
response.setContentType("text/json; charset=utf-8");
PrintWriter writer = response.getWriter();
writer.write(json.toString());
writer.flush();
}
}
/**
* 文件上传辅助类
*/
public class Uploader
{
// 输出文件地址
private String url = "";
// 上传文件名
private String fileName = "";
// 状态
private String state = "";
// 文件类型
private String type = "";
// 原始文件名
private String originalName = "";
// 文件大小
private String size = "";
private HttpServletRequest request = null;
private String title = "";
// 保存路径
private String savePath = "";
// 文件允许格式
private String[] allowFiles = { ".rar", ".doc", ".docx", ".zip", ".pdf", ".txt", ".swf", ".wmv", ".gif", ".png", ".jpg", ".jpeg", ".bmp" };
// 文件大小限制,单位KB
private int maxSize = 10000;
private String filePath = "";
private 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() throws Exception
{
boolean isMultipart = ServletFileUpload.isMultipartContent(this.request);
if (!isMultipart)
{
this.state = this.errorInfo.get("NOFILE");
return;
}
//创建该对象
DiskFileItemFactory dff = new DiskFileItemFactory();
//创建文件夹
File path = new File(savePath);
if (!path.exists())
{
path.mkdirs();
}
//指定上传文件的临时目录
dff.setRepository(path);
try
{
//创建该对象
ServletFileUpload sfu = new ServletFileUpload(dff);
//指定一次上传多个文件的总尺寸
sfu.setSizeMax(this.maxSize * 1024);
sfu.setHeaderEncoding("utf-8");
//解析request 请求,并返回FileItemIterator集合
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);
String saveFile = savePath + "/" + this.fileName;
File urlFile = new File(saveFile);
//获得文件输入流
BufferedInputStream in = new BufferedInputStream(fis.openStream());
//获得文件输出流
FileOutputStream out = new FileOutputStream(urlFile);
BufferedOutputStream output = new BufferedOutputStream(out);
//开始把文件写到你指定的上传文件夹
Streams.copy(in, output, true);
// 得到文件保存后的全路径
this.filePath = saveFile;
this.state = this.errorInfo.get("SUCCESS");
// 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");
}
}
/**
* 文件类型判断
* @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("."));
}
/**
* 获取文件名
* @param fileName
* @return
*/
private String getFileName(String fileName)
{
return fileName.substring(0, fileName.lastIndexOf("."));
}
/**
* 依据原始文件名生成新文件名
* @return
*/
private String getName(String fileName)
{
Random random = new Random();
return this.fileName = getFileName(fileName) + "#!#" + random.nextInt(10000) + System.currentTimeMillis() + this.getFileExt(fileName);
}
/**
* 根据字符串创建本地目录 并按照日期建立子目录返回
* @param path
* @return
*/
private String getFolder(String path)
{
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)
{
return DirectoryUtil.getStaticDir() + "/" + 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 String 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;
}
public String getFilePath()
{
return filePath;
}
public String getSavePath()
{
return savePath;
}
}