日期:2014-05-17  浏览次数:20762 次

用fileupload进行文件上传时出现的一点小问题
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
boolean isMultipart=ServletFileUpload.isMultipartContent(request);
if(isMultipart){
//PrintWriter out=response.getWriter();
//out.println("********");
FileItemFactory factory=new DiskFileItemFactory();
ServletFileUpload upload=new ServletFileUpload(factory);
Iterator items;
//out.println("********");
try{

//try {
items=upload.parseRequest(request).iterator();
//out.println("********");
//} catch (FileUploadException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
//out.println("********");
//}
//out.println("********");
while(items.hasNext()){
FileItem item=(FileItem)items.next();
if(!item.isFormField()){
//out.println("********");
String name=item.getName();
// out.println("上传的文件为:"+name+"<br>");
//out.println("********");
String fileName2=name.substring(name.lastIndexOf('\\')+1,name.length());
//out.println("********");
String path=request.getRealPath("file")+File.separatorChar+fileName2;
//out.println("********");
File uploadedFile=new File(path);
//out.println("********");
//try {
item.write(uploadedFile);
//out.println("********");
//} catch (Exception e) {
//out.println("********");
//e.printStackTrace();
//}
//out.println("********");
response.setContentType("text/html");
response.setCharacterEncoding("gb2312");
PrintWriter out=response.getWriter();
//out.println("********");
//out.println("保存的地址"+path);
 
out.print("上传的文件为:"+name+"<br>");
out.print("保存的地址"+path);
 
 


}
}
}catch(Exception e){
e.printStackTrace();
//out.println("********");
}
}


这段代码在执行item.write(uploadedFile)时会有异常,整个程序的执行结果是一个空白页,真不知道为什么。

------解决方案--------------------
给你贴一个我写的
Java code
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        try {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setHeaderEncoding("utf-8");
            
            if(!upload.isMultipartContent(request)){
                return;
            }
            List<FileItem> list = upload.parseRequest(request);
            for(FileItem item:list){
                if(item.isFormField()){
                    String name = item.getFieldName();
                    String value = item.getString("utf-8");
                    System.out.println(name+"="+value);
                }
                else{
                    InputStream in = item.getInputStream();
                    String realPath = getServletContext().getRealPath("/WEB-INF/upload");
                    String name = item.getName();
                    String realName = name.substring(name.lastIndexOf('\\')+1);