在web端,想用jsp写个文件上传,发现如何只用普通的<input type=”file” ·····>来的写话是不能把文件和表单其他内容一起上传。
于是尝试用了SmartUpload,发现SmartUpload对表单的中文能里处理会有乱码,即使用了
new String(mySmartUpload.getRequest().getParameter("news_type").trim().getBytes(),"utf-8");
的话,接收表单内容是即使显示中文,但也极其不稳定,有些字是中文,有些字是乱码。
最后改用了commons—fileuoload框架。能顺利解决中文乱码问题。代码如下:
protectedvoid doPost(HttpServletRequest request,HttpServletResponse response) throwsServletException, IOException {
response.setContentType("text/html;chaeset=utf-8");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
boolean isMultipart = ServletFileUpload.isMultipartContent(request);//检查输入请求是否为multipart表单数据。
if (isMultipart == true) {
FileItemFactory factory = new DiskFileItemFactory();//为该请求创建一个DiskFileItemFactory对象,通过它来解析请求。执行解析后,所有的表单项目都保存在一个List中。
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = null;
try {
items =upload.parseRequest(request);
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Iterator<FileItem> itr = items.iterator();
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
//检查当前项目是普通表单项目还是上传文件。
if (item.isFormField()) {//如果是普通表单项目,显示表单内容。
String fieldName =item.getFieldName();
if (fieldName.equals("name")) //对应demo1.html中type="text" name="name"
out.print("the field name is " + item.getString("utf-8"));//显示表单内容。
out.print("<br>");
} else {//如果是上传文件,显示文件名。
String fileName=item.getName();
String path="F:/img";
File fullFile=new File(item.getName());
File savedFile=new File(path,fullFile.getName());
try {
item.write(savedFile);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.print("the upload file name is " + item.getName());
out.print("<br>");
}
}
} else {
out.print("theenctype must be multipart/form-data");
}
}
}