案例34-文件上传

1 案例分析

1 文件上传原理分析

2 代码实现

1 form.html

 vf<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <form action="/WEB32/fileuploadServlet2" method="post" enctype="multipart/form-data">
        <input type="text" name="username"><br>
        <input type="file" name="filename"><br>
        <input type="submit" value="上传文件">
    </form>
</body>
</html>

2 FileuploadServlet入门代码

package www.test.web.servlet;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class FileUploadServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        try {
            //接收文件上传
            
            // 1 创建磁盘文件项工厂
            DiskFileItemFactory factory = new DiskFileItemFactory();
            // 2创建文件上传核心类
            ServletFileUpload upload = new ServletFileUpload(factory);
            
            // 3解析request---获得文件项集合
            List<FileItem> parseRequest = upload.parseRequest(request);
            
            // 4遍历文件项集合
            for (FileItem fileItem : parseRequest) {
                // 5判断普通表单项/文件上传项
                boolean formField = fileItem.isFormField(); //是不是一个普通的表单项
                if(formField){
                    //普通表单项
                    String fieldName = fileItem.getFieldName();
                    String filedValue = fileItem.getString();
                    System.out.println(fieldName+"::::"+filedValue);
                }else{
                    //文件上传项
                    //获得上传文件的名称
                    
                    //不同的浏览器提交的文件名是不一样的,有些浏览器提交的文件名是带有路径的,
                    //如:c:\nihao\a.txt,而有些只是单纯的文件名,如:a.txt  
                    //处理获取到的上传文件的文件名的路径部分,只保留文件名部分 
                    String fileName = fileItem.getName();
                    fileName = fileName.substring(fileName.lastIndexOf("\\")+1);
                    
                    
                    
                    //获得上传文件的内容
                    InputStream in = fileItem.getInputStream();
                    //将in流中的数据拷贝到服务器上
                    String realPath = this.getServletContext().getRealPath("/upload");
                    OutputStream out = new FileOutputStream(realPath+"/"+fileName);
                    
                    int len = 0;
                    byte[] buffer = new byte[1024];
                    while((len=in.read(buffer))!=-1){
                        out.write(buffer, 0, len);
                    }
                    
                    //关闭资源
                    in.close();
                    out.close();
                }
                
            }
        } catch (FileUploadException e) {
            
            e.printStackTrace();
        }
        
        
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}

3 FileuploadServlet2详细代码

package www.test.web.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

public class FileUploadServlet2 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

            try {
                // 接收文件上传
                
                // 1 创建磁盘文件项工厂
                //作用: 设置缓存文件的大小  设置临时文件的存储位置
                String path_temp = this.getServletContext().getRealPath("temp");
                //DiskFileItemFactory factory = new DiskFileItemFactory(1204*1204,new File(path_temp));
                
                //DiskFileItemFactory factory = new DiskFileItemFactory(1204*1204,new File(path_temp));
                //上面的这句代码也可以换成下面的三条语句
                DiskFileItemFactory factory =  new DiskFileItemFactory();
                //只有文件的大小大于缓存的大小才会产生临时文件
                factory.setSizeThreshold(1024*1024*10); //设置缓存的大小
                factory.setRepository(new File(path_temp)); //设置临时文件的目录
                
                
                // 2 创建文件上传核心类
                ServletFileUpload upload = new ServletFileUpload(factory);
                //设置上传文件的名称的编码
                upload.setHeaderEncoding("UTF-8");
                
                
                //ServletFileUpload的API
                boolean multipartContent = upload.isMultipartContent(request); //判断表单是不是文件上传的表单
                if(multipartContent){
                    //是文件上传的表单
                    // 3 ******解析request----  获得文件项集合
                List<FileItem> parseRequest = upload.parseRequest(request);
                if(parseRequest!=null){
                    // 4 遍历文件项集合 
                    for (FileItem fileItem : parseRequest) {
                        // 5判断是普通表单项/文件上传项
                        boolean formField = fileItem.isFormField();//是不是一个普通的表单项
                        if(formField){
                            //普通表单项 username = zhangsan
                            String fieldName = fileItem.getFieldName();
                            String fieldValue = fileItem.getString("UTF-8");//对普通表单项的内容进行编码
                            
                            System.out.println(fieldName+"------"+fieldValue);
                            
                            // 注意:当表单是enctype="multipart/form-data"时 request.getParameter相关的方法都失效
                            //String parameter = request.getParameter("username");获取不到数据
                            
                        }else{
                            // 文件上传项
                            String fileName = fileItem.getName();//获取文件名
                            //不同的浏览器提交的文件名是不一样的,有些浏览器提交的文件名是带有路径的,
                            //如:c:\nihao\a.txt,而有些只是单纯的文件名,如:a.txt  
                            //处理获取到的上传文件的文件名的路径部分,只保留文件名部分 
                            fileName = fileName.substring(fileName.lastIndexOf("\\")+1);
                            
                            
                            //获得上传文件的内容  也是就获得与文件关联的输入流
                            InputStream in = fileItem.getInputStream();
                                //获取存储文件的绝对地址
                            String path_store = this.getServletContext().getRealPath("upload");
                            OutputStream out = new FileOutputStream(path_store+"/"+fileName);
                                //上传文件实际上就是复制文件到服务器 直接使用工具类
                            IOUtils.copy(in, out);
                                //关闭资源
                            in.close();
                            out.close();
                            
                            //删除临时文件
                            fileItem.delete();
                            
                            }
                        }
                    }
                }else{
                    //不是文件上传表单
                    //使用原始的表单数据的获取方式
                }
            } catch (FileUploadException e) {
                
                e.printStackTrace();
            }
        
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}

 

3 文件上传知识点

4 文件上传的一个常见问题的解决

1 form.jsp代码

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    <form action="${pageContext.request.contextPath}/fileUploadServlet" 
    method="post" enctype="multipart/form-data">
        <input type="text" name="username">
        <input type="file" name="filename">
        <input type="submit" value="上传文件">
    </form>
</body>
</html>

2 FileuploadServlet代码

package www.test.web.servlet;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class FileUploadServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        try {
            //接收文件上传
            
            // 1 创建磁盘文件项工厂
            DiskFileItemFactory factory = new DiskFileItemFactory();
            // 2创建文件上传核心类
            ServletFileUpload upload = new ServletFileUpload(factory);
            
            // 3解析request---获得文件项集合
            List<FileItem> parseRequest = upload.parseRequest(request);
            
            // 4遍历文件项集合
            for (FileItem fileItem : parseRequest) {
                // 5判断普通表单项/文件上传项
                boolean formField = fileItem.isFormField(); //是不是一个普通的表单项
                if(formField){
                    //普通表单项
                    String fieldName = fileItem.getFieldName();
                    String filedValue = fileItem.getString();
                    System.out.println(fieldName+"::::"+filedValue);
                }else{
                    //文件上传项
                    //获得上传文件的名称
                    
                    //不同的浏览器提交的文件名是不一样的,有些浏览器提交的文件名是带有路径的,
                    //如:c:\nihao\a.txt,而有些只是单纯的文件名,如:a.txt  
                    //处理获取到的上传文件的文件名的路径部分,只保留文件名部分 
                    String fileName = fileItem.getName();
                    //fileName = fileName.substring(fileName.lastIndexOf("\\")+1);
                    
                    
                    
                    //获得上传文件的内容
                    InputStream in = fileItem.getInputStream();
                    //将in流中的数据拷贝到服务器上
                    String realPath = this.getServletContext().getRealPath("/upload");
                    OutputStream out = new FileOutputStream(realPath+"/"+fileName);
                    
                    int len = 0;
                    byte[] buffer = new byte[1024];
                    while((len=in.read(buffer))!=-1){
                        out.write(buffer, 0, len);
                    }
                    
                    //关闭资源
                    in.close();
                    out.close();
                }
                
            }
        } catch (FileUploadException e) {
            
            e.printStackTrace();
        }
        
        
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}

3 运行过程中出现的问题

4 解决办法

出现上述问题的原因是:不同的浏览器提交的文件名是不一样的,有些浏览器提交的文件名是带有路径的,

如:c:\nihao\a.txt,而有些只是单纯的文件名,如:a.txt 处理获取到的上传文件的文件名的路径部分,只保留文件名部分

 

 

 

posted @ 2018-02-15 15:37  Jepson6669  阅读(319)  评论(0编辑  收藏  举报