您的位置:首页 > 其它

使用commons-fileupload实现表单提交上传,并取出参数,解决了乱码

2009-09-29 22:21 543 查看
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();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐