File tempfile = null;
List itemsList = null;
try {
tempfile = new File(System.getProperty("java.io.tmpdir"));
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
diskFileItemFactory.setSizeThreshold(4096);
diskFileItemFactory.setRepository(tempfile);
ServletFileUpload sfu = new ServletFileUpload(diskFileItemFactory);
sfu.setHeaderEncoding("utf-8");
sfu.setSizeMax(4194304);
itemsList = sfu.parseRequest(request);
} catch (FileUploadException e) {
e.printStackTrace();
}
Iterator itr = itemsList.iterator();
String fileName = null;
while (itr.hasNext()) {
FileItem fi = (FileItem) itr.next();
/*********************************取出表单域中的参数以及对应提交的值***************/
if (fi.isFormField()) {
if (fi.getFieldName().equals("receiver")) {
//解决中文参数乱码问题
receiver = new String(fi.getString("UTF-8"));
}
if (fi.getFieldName().equals("sender")) {
//解决中文参数乱码问题
sender = new String(fi.getString("UTF-8"));
}
if (fi.getFieldName().equals("title")) {
//解决中文参数乱码问题
title = new String(fi.getString("UTF-8"));
//解决中文参数乱码问题
}
if (fi.getFieldName().equals("content")) {
//解决中文参数乱码问题
content = new String(fi.getString("UTF-8"));
}
} else {
/*******************************上传文件部分*****************************/
fileName = fi.getName();
if (fileName != null&&fileName.length()!=0) {
File fullFile = new File(fi.getName());
String fileType=fullFile.getName().substring(fullFile.getName().lastIndexOf("."));
//避免上传文件重名
String saveFileName=new SimpleDateFormat("yyMMddHHssmm").format(new Date())+String.valueOf((int)Math.random()*1000)+fileType;
//文件上传到的文件夹在web。xml中进行配置,通过servletcontext取得
String uploadPath=getServletContext().getInitParameter("uploadPath");
File filePath=new File(uploadPath);
if(!filePath.exists()){
filePath.mkdirs();
}
File savedFile = new File(
uploadPath, saveFileName);
try {
fi.write(savedFile);
} catch (Exception e) {
e.printStackTrace();
}
}