java web-- upload and dowload(2)

 1. 文件下载的需求: spring整合的上传下载

         1). 在文件上传成功后的 success.jsp 页面上提供一个 "下载资源" 的超链接

         2). 点击 "下载资源" 的超链接, 会把请求发送到 Servlet, 读取数据库, 在页面上显示可以下载的资源信息

                   FileName: 11.尚硅谷_JavaWEB_监听器.pptx
                   Desc: AA
            下载

                    FileName: 12.尚硅谷_JavaWEB_文件的上传和下载.pptx
                    Desc: BB
             下载

          3). 再点击下载, 即可完成对应文件的下载.

  2. 文件的下载:

          1). 步骤:

                I. 设置 contentType 响应头: 设置响应的类型是什么 ? 通知浏览器是个下载的文件

                            response.setContentType("application/x-msdownload");

                II. 设置 Content-Disposition 响应头: 通知浏览器不再有浏览器来自行处理(或打开)要下载的文件, 而由用户手工完成

                            response.setHeader("Content-Disposition", "attachment;filename=abc.txt");

               III. 具体的文件: 可以调用 response.getOutputStream 的方式, 以 IO 流的方式发送给客户端.

                      OutputStream out = response.getOutputStream();
                      String pptFileName = "C:\\Users\\Think Pad\\Desktop\\__正在上课__\\11.尚硅谷_JavaWEB_监听器.pptx";

                      InputStream in = new FileInputStream(pptFileName);

                       byte [] buffer = new byte[1024];
                         int len = 0;

                       while((len = in.read(buffer)) != -1){
                                   out.write(buffer, 0, len);
                          }

                            in.close();

   3. 如何修改小工具或框架的源代码 ?

           1). 原则: 能不修改就不修改.

           2). 修改的方法:

                  > 修改源代码, 替换 jar 包中对应的 class 文件.
                  > 在本地新建相同的包, 和类, 在这个类中修改即可.

   4. 使用 fileupload 组件完成文件的上传应用

          1). 需求:

                  I. 上传
                       > 在 upload.jsp 页面上使用 jQuery 实现 "新增一个附件", "删除附件". 但至少需要保留一个.
                       > 对文件的扩展名和文件的大小进行验证. 以下的规则是可配置的. 而不是写死在程序中的.
                       >> 文件的扩展名必须为 .pptx, docx, doc
                       >> 每个文件的大小不能超过 1 M
                       >> 总的文件大小不能超过 5 M.
                       > 若验证失败, 则在 upload.jsp 页面上显示错误消息:
                       >> 若某一个文件不符合要求: xxx 文件扩展名不合法 或 xxx 文件大小超过 1 M
                       >> 总的文件大小不能超过 5 M.
                       > 若验证通过, 则进行文件的上传操作
                       >> 文件上传, 并给一个不能和其他文件重复的名字, 但扩展名不变
                       >> 在对应的数据表中添加一条记录.
                           id file_name file_path file_desc

                       >> 进行文件上传时, 表单需要做的准备:

                      1). 请求方式为 POST: <form action="uploadServlet" method="post" ... >
                      2). 使用 file 的表单域: <input type="file" name="file"/>
                      3). 使用 multipart/form-data 的请求编码方式: <form action="uploadServlet" method="post" enctype="multipart/form-data">

                           <form action="uploadServlet" method="post" enctype="multipart/form-data">
                             File:  <input type="file" name="file"/>
                                     <input type="submit" value="Submit"/>
                           </form>

                 II. 下载

                       问题: 如何清除上传文件临时文件夹的文件.         

           2). 关于 enctype:

                 > application/x-www-form-urlencoded:表单 enctype 属性的默认值。这种编码方案使用有限的字符集,当使用了非字母和数字时,
                     必须用”%HH”代替(H 代表十六进制数字)。对于大容量的二进制数据或包含非 ASCII 字符的文本来说,这种编码不能满足要求。
                > multipart/form-data:form 设定了enctype=“multipart/form-data”属性后,表示表单以二进制传输数据

     5. 服务端:

              1). 不能再使用 request.getParameter() 等方式获取请求信息. 获取不到, 因为请求的编码方式已经改为 multipart/form-data, 以
                    二进制的方式来提交请求信息.

              2). 可以使用输入流的方式来获取. 但不建议这样做.

              3). 具体使用 commons-fileupload 组件来完成文件的上传操作.

                I. 搭建环境: 加入
                           commons-fileupload-1.2.1.jar
                           commons-io-2.0.jar

                II. 基本思想:

                         > commons-fileupload 可以解析请求, 得到一个 FileItem 对象组成的 List
                         > commons-fileupload 把所有的请求信息都解析为 FileItem 对象, 无论是一个一般的文本域还是一个文件域.
                         > 可以调用 FileItem 的 isFormField() 方法来判断是一个 表单域 或不是表单域(则是一个文件域)
                         > 再来进一步获取信息
                              if (item.isFormField()) {
                                         String name = item.getFieldName();
                                         String value = item.getString();
                                               ...
                                 }
                              if (!item.isFormField()) {
                                            String fieldName = item.getFieldName();
                                            String fileName = item.getName();
                                            String contentType = item.getContentType();
                                            boolean isInMemory = item.isInMemory();
                                            long sizeInBytes = item.getSize();
                                            InputStream uploadedStream = item.getInputStream();
                                                ...
                                            uploadedStream.close();
                                       }

                    III. 如何得到 List<FileItem> 对象.

                           > 简单的方式

                                       // Create a factory for disk-based file items
                              FileItemFactory factory = new DiskFileItemFactory();
                                       // Create a new file upload handler
                              ServletFileUpload upload = new ServletFileUpload(factory);
                                       // Parse the request
                              List /* FileItem */ items = upload.parseRequest(request);
                          > 复杂的方式: 可以为文件的上传加入一些限制条件和其他的属性
                            // Create a factory for disk-based file items
                            DiskFileItemFactory factory = new DiskFileItemFactory();

                          //设置内存中最多可以存放的上传文件的大小, 若超出则把文件写到一个临时文件夹中. 以 byte 为单位
                               factory.setSizeThreshold(yourMaxMemorySize);
                          //设置那个临时文件夹
                               factory.setRepository(yourTempDirectory);
                          // Create a new file upload handler
                               ServletFileUpload upload = new ServletFileUpload(factory);
                         //设置上传文件的总的大小. 也可以设置单个文件的大小.
                               upload.setSizeMax(yourMaxRequestSize);
                         // Parse the request
                            List /* FileItem */ items = upload.parseRequest(request);

 6.代码区

 

package com.atguigu.download.servlet;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

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

/**
 * Servlet implementation class DownloadServlet
 */
public class DownloadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/x-msdownload"); 
        
        String fileName = "aaattt.doc";
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        
        OutputStream out = response.getOutputStream();
        String pptFileName = "D:/files/aaattt.doc";
        
        InputStream in = new FileInputStream(pptFileName);
        
        byte [] buffer = new byte[1024];
        int len = 0;
        
        while((len = in.read(buffer)) != -1){
            out.write(buffer, 0, len);
        }
        
        in.close();
    }

}
DownloadServlet   下载的servelet
package com.atguigu.fileupload.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;

public class UploadServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

        // 1. 得到 FileItem 的集合 items
        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();
        
//        FileCleaningTracker fileCleaningTracker = 
//                FileCleanerCleanup.getFileCleaningTracker(getServletContext());
//        factory.setFileCleaningTracker(fileCleaningTracker);
        
        // Set factory constraints
        factory.setSizeThreshold(1024 * 500);
        File tempDirectory = new File("d:\\tempDirectory");
        factory.setRepository(tempDirectory);

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Set overall request size constraint
        upload.setSizeMax(1024 * 1024 * 5);

        // Parse the request
        try {
            List<FileItem> /* FileItem */items = upload.parseRequest(request);

            // 2. 遍历 items:
            for (FileItem item : items) {
                // 若是一个一般的表单域, 打印信息
                if (item.isFormField()) {
                    String name = item.getFieldName();
                    String value = item.getString();
                     /*desc: Asd
                       interesting: Reading
                       interesting: Sports*/
                    System.out.println(name + ": " + value);
                    
                    
                }
                // 若是文件域则把文件保存到 d:\\files 目录下.
                else {
                    String fieldName = item.getFieldName();
                    String fileName = item.getName();
                    String contentType = item.getContentType();
                    long sizeInBytes = item.getSize();

                    System.out.println(fieldName);
                    System.out.println(fileName);
                    System.out.println(contentType);
                    System.out.println(sizeInBytes);
                     /*file
                       aaattt.doc
                       application/msword
                       427008*/
                    InputStream in = item.getInputStream();
                    byte[] buffer = new byte[1024];
                    int len = 0;

                    fileName = "d:\\files\\" + fileName;
                    System.out.println(fileName);
                     //d:\files\aaattt.doc
                    OutputStream out = new FileOutputStream(fileName);

                    while ((len = in.read(buffer)) != -1) {
                        out.write(buffer, 0, len);
                    }

                    out.close();
                    in.close();
                }
            }

        } catch (FileUploadException e) {
            e.printStackTrace();
        }

    }

}
UploadServlet     上传的servlet
package com.atguigu.fileupload.app.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.atguigu.fileupload.app.beans.FileUploadBean;
import com.atguigu.fileupload.app.db.UploadFileDao;
import com.atguigu.fileupload.app.exception.InvalidExtNameException;
import com.atguigu.fileupload.app.utils.FileUploadAppProperties;
import com.atguigu.fileupload.app.utils.FileUtils;

public class FileUploadServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;
    
    private static final String FILE_PATH = "/WEB-INF/files/";
    
    private static final String TEMP_DIR = "d:\\tempDirectory";
    
    private UploadFileDao dao = new UploadFileDao();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        request.setCharacterEncoding("UTF-8");
        
        String path = null;
        
        //获取 ServletFileUpload 对象. 
        ServletFileUpload upload = getServletFileUpload();
        
        try {
            
            //把需要上传的 FileItem 都放入到该 Map 中
            //键: 文件的待存放的路径, 值: 对应的 FileItem 对象
            Map<String, FileItem> uploadFiles = new HashMap<String, FileItem>();
            
            //解析请求, 得到 FileItem 的集合.
            List<FileItem> items = upload.parseRequest(request);
            
            //1. 构建 FileUploadBean 的集合, 同时填充 uploadFiles
            List<FileUploadBean> beans = buildFileUploadBeans(items, uploadFiles);
            
            //2. 校验扩展名:
            vaidateExtName(beans);

            //3. 校验文件的大小: 在解析时, 已经校验了, 我们只需要通过异常得到结果. 
            
            //4. 进行文件的上传操作.
            upload(uploadFiles);
            
            //5. 把上传的信息保存到数据库中
            saveBeans(beans);
            
            //6. 删除临时文件夹的临时文件
            FileUtils.delAllFile(TEMP_DIR);
            
            path = "/app/success.jsp";
             
            
        } catch (Exception e) {
            e.printStackTrace();
            path = "/app/upload.jsp";
            request.setAttribute("message", e.getMessage());
        }
        
        request.getRequestDispatcher(path).forward(request, response);
    }

    private void saveBeans(List<FileUploadBean> beans) {
        dao.save(beans); 
    }

    /**
     * 文件上传前的准备工作. 得到 filePath 和 InputStream
     * @param uploadFiles
     * @throws IOException
     */
    private void upload(Map<String, FileItem> uploadFiles) throws IOException {
        for(Map.Entry<String, FileItem> uploadFile: uploadFiles.entrySet()){
            String filePath = uploadFile.getKey();
            FileItem item = uploadFile.getValue();
            
            upload(filePath, item.getInputStream());
        }
    }

    /**
     * 文件上传的 IO 方法.
     * 
     * @param filePath
     * @param inputStream
     * @throws IOException
     */
    private void upload(String filePath, InputStream inputStream) throws IOException {
        OutputStream out = new FileOutputStream(filePath);
        
        byte [] buffer = new byte[1024];
        int len = 0;
        
        while((len = inputStream.read(buffer)) != -1){
            out.write(buffer, 0, len);
        }
        
        inputStream.close();
        out.close();
        
        System.out.println(filePath); 
    }

    /**
     * 校验扩展名是否合法
     * @param beans: 
     */
    private void vaidateExtName(List<FileUploadBean> beans) {
        String exts = FileUploadAppProperties.getInstance().getProperty("exts");
        List<String> extList = Arrays.asList(exts.split(","));
        System.out.println(extList);
        
        for(FileUploadBean bean: beans){
            String fileName = bean.getFileName();
            System.out.println(fileName.indexOf(".")); 
            
            String extName = fileName.substring(fileName.lastIndexOf(".") + 1);
            System.out.println(extName); 
            
            if(!extList.contains(extName)){
                throw new InvalidExtNameException(fileName + "文件的扩展名不合法");
            }
        }
    }

    /**
     * 利用传入的 FileItem 的集合, 构建 FileUploadBean 的集合, 同时填充 uploadFiles
     * 
     * FileUploadBean 对象封装了: id, fileName, filePath, fileDesc
     * uploadFiles: Map<String, FileItem> 类型, 存放文件域类型的  FileItem. 键: 待保存的文件的名字 ,值: FileItem 对象
     * 
     * 构建过程:
     * 1. 对传入 FileItem 的集合进行遍历. 得到 desc 的那个 Map. 键: desc 的 fieldName(desc1, desc2 ...). 
     * 值: desc 的那个输入的文本值
     * 
     * 2. 对传入 FileItem 的集合进行遍历. 得到文件域的那些 FileItem 对象, 构建对应的 key (desc1 ....) 来获取其 desc.
     * 构建的 FileUploadBean 对象, 并填充 beans 和 uploadFiles
     * 
     * @param items
     * @param uploadFiles
     * @return
     * @throws UnsupportedEncodingException 
     */
    private List<FileUploadBean> buildFileUploadBeans(List<FileItem> items, Map<String, FileItem> uploadFiles) throws UnsupportedEncodingException {
        List<FileUploadBean> beans = new ArrayList<>();
        
        Map<String, String> descs = new HashMap<>();
        
        for(int i = 0; i < items.size(); i++){
            FileItem item = items.get(i);
            
            if(item.isFormField()){
                //desc1 或 desc2 ...
                String fieldName = item.getFieldName();
                String desc = item.getString("UTF-8");
                
                descs.put(fieldName, desc);
            }
        }
        
        for(int i = 0; i < items.size(); i++){
            FileItem item = items.get(i);
            FileUploadBean bean = null;
            if(!item.isFormField()){
                String fieldName = item.getFieldName();
                String descName = "desc" + fieldName.substring(fieldName.length() - 1);
                String desc = descs.get(descName); 
                
                //对应文件名
                String fileName = item.getName();
                String filePath = getFilePath(fileName);
                
                bean = new FileUploadBean(fileName, filePath, desc);
                beans.add(bean);
                
                uploadFiles.put(bean.getFilePath(), item);
            }            
        }
        
        return beans;
    }

    /**
     * 根据跟定的文件名构建一个随机的文件名
     * 1. 构建的文件的文件名的扩展名和给定的文件的扩展名一致
     * 2. 利用 ServletContext 的 getRealPath 方法获取的绝对路径
     * 3. 利用了 Random 和 当前的系统时间构建随机的文件的名字
     * 
     * @param fileName
     * @return
     */
    private String getFilePath(String fileName) {
        String extName = fileName.substring(fileName.lastIndexOf("."));
        Random random = new Random();
        
        String filePath = getServletContext().getRealPath(FILE_PATH) + "\\" + System.currentTimeMillis() + random.nextInt(100000) + extName;
        return filePath;
    }

    /**
     * 构建 ServletFileUpload 对象
     * 从配置文件中读取了部分属性, 用户设置约束. 
     * 该方法代码来源于文档. 
     * @return
     */
    private ServletFileUpload getServletFileUpload() {
        String fileMaxSize = FileUploadAppProperties.getInstance().getProperty("file.max.size");
        String totalFileMaxSize = FileUploadAppProperties.getInstance().getProperty("total.file.max.size");
        
        DiskFileItemFactory factory = new DiskFileItemFactory();
        
        factory.setSizeThreshold(1024 * 500);
        File tempDirectory = new File(TEMP_DIR);
        factory.setRepository(tempDirectory);

        ServletFileUpload upload = new ServletFileUpload(factory);

        upload.setSizeMax(Integer.parseInt(totalFileMaxSize));
        upload.setFileSizeMax(Integer.parseInt(fileMaxSize));
        
        return upload;
    }

}
FileUploadServlet   把文件的地址和文件名和描述存储在数据库中
package com.atguigu.fileupload.app.beans;

import java.util.ArrayList;
import java.util.List;

import com.google.gson.Gson;


public class FileUploadBean {

    public static void main(String[] args) {
        FileUploadBean bean = new FileUploadBean("ABC", "e:\\abc.txt", "aabbcc");
        Gson gson = new Gson();
        String jsonStr = gson.toJson(bean);
        System.out.println(jsonStr);
        
        List<FileUploadBean> beans = new ArrayList<>();
        beans.add(bean);
        beans.add(new FileUploadBean("def", "e:\\def.txt", "ddeeff"));
        jsonStr = gson.toJson(beans);
        System.out.println(jsonStr);
    }
    
    private Integer id;
    // 文件名
    private String fileName;
    // 文件的路径
    private String filePath;
    // 文件的描述
    private String fileDesc;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public String getFilePath() {
        return filePath;
    }

    public void setFilePath(String filePath) {
        this.filePath = filePath;
    }

    public String getFileDesc() {
        return fileDesc;
    }

    public void setFileDesc(String fileDesc) {
        this.fileDesc = fileDesc;
    }

    public FileUploadBean(String fileName, String filePath, String fileDesc) {
        super();
        this.fileName = fileName;
        this.filePath = filePath;
        this.fileDesc = fileDesc;
    }

    public FileUploadBean() {
        // TODO Auto-generated constructor stub
    }
}
FileUploadBean
package com.atguigu.fileupload.app.db;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ArrayHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

public class DAO<T>{

    public static QueryRunner runner = new QueryRunner();
    
    private Class<T> clazz;
    
    public DAO() {
        
        Type type = getClass().getGenericSuperclass();
        
        if(type instanceof ParameterizedType){
            ParameterizedType pt = (ParameterizedType) type;
            
            Type [] parameterArgs = pt.getActualTypeArguments();
            
            if(parameterArgs != null && parameterArgs.length > 0){
                if(parameterArgs[0] instanceof Class){
                    clazz = (Class<T>) parameterArgs[0]; 
                }
            }
        }
        
    }
    
    protected void update(Connection conn, String sql, Object ... args) throws SQLException{
        runner.update(conn, sql, args);
    }
    
    protected T get(Connection conn, String sql, Object ... args) throws SQLException{
        return runner.query(conn, sql, new BeanHandler<>(clazz), args); 
    }
    
    protected List<T> getForList(Connection conn, String sql, Object ... args) throws SQLException{
        return runner.query(conn, sql, new BeanListHandler<>(clazz), args); 
    }
    
    protected <E> E getValue(Connection conn, String sql, Object ... args) throws SQLException{
        E result = null;
        result = (E) runner.query(conn, sql, new ArrayHandler(), args)[0];
        return result;
    }
    
}
DAO<T>
package com.atguigu.fileupload.app.db;

public class DBException extends RuntimeException {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    public DBException() {
        // TODO Auto-generated constructor stub
    }
    
    public DBException(String msg) {
        super(msg);
    }
    
    public DBException(String msg, Exception ex) {
        super(msg, ex);
    }
}
DBException
package com.atguigu.fileupload.app.db;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class JDBCUtils {

    private static DataSource dataSource = null;
    
    static{
        dataSource = new ComboPooledDataSource("javawebapp");
    }
    
    public static Connection getConnection(){  
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
            throw new DBException("");
        }
    }
 
    public static void release(Connection connection) {
        try {
            if(connection != null){
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
            throw new DBException("");
        }
    }
    
}
JDBCUtils
package com.atguigu.fileupload.app.db;

import java.sql.Connection;
import java.util.List;

import com.atguigu.fileupload.app.beans.FileUploadBean;

public class UploadFileDao extends DAO<FileUploadBean>{
    
    public List<FileUploadBean> getFiles(){
        
        Connection conn = null;
        
        try {
            conn = JDBCUtils.getConnection();
            String sql = "SELECT id, file_name fileName, file_path filePath, " +
                    "file_desc fileDesc FROM upload_files";
            return getForList(conn, sql);            
        } catch (Exception e) {
            e.printStackTrace();
        } finally{
            JDBCUtils.release(conn);
        }
        
        return null;
    } 
    
    public void save(List<FileUploadBean> uploadFiles){
        
        Connection conn = null;
        
        try {
            conn = JDBCUtils.getConnection();
            String sql = "INSERT INTO upload_files (file_name, file_path, file_desc) VALUES " +
                    "(?, ?, ?)";
            for(FileUploadBean file: uploadFiles){
                update(conn, sql, file.getFileName(), file.getFilePath(), file.getFileDesc());
            }            
        } catch (Exception e) {
            e.printStackTrace();
        } finally{
            JDBCUtils.release(conn);
        }
        
    }
    
}
UploadFileDao
package com.atguigu.fileupload.app.exception;

public class InvalidExtNameException extends RuntimeException{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    public InvalidExtNameException(String msg) {
        super(msg);
    }
}
InvalidExtNameException
package com.atguigu.fileupload.app.listener;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Properties;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import com.atguigu.fileupload.app.utils.FileUploadAppProperties;

/**
 * Application Lifecycle Listener implementation class FileUploadAppListener
 *
 */
public class FileUploadAppListener implements ServletContextListener {

    /**
     * Default constructor. 
     */
    public FileUploadAppListener() {
        // TODO Auto-generated constructor stub
    }

    /**
     * @see ServletContextListener#contextInitialized(ServletContextEvent)
     */
    public void contextInitialized(ServletContextEvent arg0) {
        InputStream in = getClass().getClassLoader().getResourceAsStream("/upload.properties");
        
        Properties properties = new Properties();
        try {
            properties.load(in);
            
            for(Map.Entry<Object, Object> prop: properties.entrySet()){
                String propertyName = (String) prop.getKey();
                String propertyValue = (String) prop.getValue();
                
                FileUploadAppProperties.getInstance().addProperty(propertyName, propertyValue);
            }
            
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @see ServletContextListener#contextDestroyed(ServletContextEvent)
     */
    public void contextDestroyed(ServletContextEvent arg0) {
        // TODO Auto-generated method stub
    }
    
}
FileUploadAppListener
package com.atguigu.fileupload.app.utils;

import java.util.HashMap;
import java.util.Map;

public class FileUploadAppProperties {
    
    private Map<String, String> properties = new HashMap<>();
    
    private FileUploadAppProperties(){}
    
    private static FileUploadAppProperties instance = new FileUploadAppProperties();
    
    public static FileUploadAppProperties getInstance() {
        return instance;
    }
    
    public void addProperty(String propertyName, String propertyValue){
        properties.put(propertyName, propertyValue);
    }
    
    public String getProperty(String propertyName){
        return properties.get(propertyName);
    }
    
}
FileUploadAppProperties
package com.atguigu.fileupload.app.utils;

import java.io.File;

public class FileUtils {

    /**
     * 删除文件夹
     * @param folderPath:  文件夹完整绝对路径
     */
    public static void delFolder(String folderPath) {
        try {
            // 删除完里面所有内容
            delAllFile(folderPath);
            String filePath = folderPath;
            filePath = filePath.toString();
            java.io.File myFilePath = new java.io.File(filePath);
            // 删除空文件夹
            myFilePath.delete();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除指定文件夹下所有文件
     * @param path: 文件夹完整绝对路径
     * @return
     */
    public static boolean delAllFile(String path) {
        boolean flag = false;
        File file = new File(path);
        if (!file.exists()) {
            return flag;
        }
        if (!file.isDirectory()) {
            return flag;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                temp.delete();
            }
            if (temp.isDirectory()) {
                // 先删除文件夹里面的文件
                delAllFile(path + "/" + tempList[i]);
                // 再删除空文件夹
                delFolder(path + "/" + tempList[i]);
                flag = true;
            }
        }
        
        return flag;
    }

}
FileUtils
<?xml version="1.0" encoding="UTF-8"?>

<c3p0-config>

  <named-config name="javawebapp"> 
  
      <property name="user">root</property>
    <property name="password">123456</property>
    <property name="jdbcUrl">jdbc:mysql:///test</property>
    <property name="driverClass">com.mysql.jdbc.Driver</property>
  
    <property name="acquireIncrement">2</property>
    <property name="initialPoolSize">5</property>
    <property name="minPoolSize">5</property>
    <property name="maxPoolSize">10</property>

    <property name="maxStatements">20</property> 
    <property name="maxStatementsPerConnection">5</property>

  </named-config>
</c3p0-config>
c3p0-config.xml
exts=pptx,docx,doc
file.max.size=1048576
total.file.max.size=5242880
upload.properties
<%@ 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=UTF-8">
<title>Insert title here</title>
</head>
<body>
    
    <h4>文件上传成功!</h4>
    
</body>
</html>
success.jsp  app
<%@ 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=UTF-8">

<title>Insert title here</title>
<script type="text/javascript" src="${pageContext.request.contextPath }/scripts/jquery-1.7.2.js"></script>
<script type="text/javascript">
    
    $(function(){
        
        var i = 2;
        
        $("#addFile").click(function(){
            $(this).parent().parent().before("<tr class='file'><td>File" 
                    + i + ":</td><td><input type='file' name='file" 
                    + i + "'/></td></tr>"
                    + "<tr class='desc'><td>Desc" 
                    + i + ":</td><td><input type='text' name='desc" 
                    + i + "'/><button id='delete" 
                    + i + "'>删除</button></td></tr>");
            i++;
            
            //获取新添加的删除按钮
            $("#delete" + (i-1)).click(function(){
                var $tr = $(this).parent().parent();
                $tr.prev("tr").remove();
                $tr.remove();
                
                //对 i 重写排序
                $(".file").each(function(index){
                    var n = index + 1;
                    
                    $(this).find("td:first").text("File" + n);
                    $(this).find("td:last input").attr("name", "file" + n);
                });
                
                $(".desc").each(function(index){
                    var n = index + 1;
                    
                    $(this).find("td:first").text("Desc" + n);
                    $(this).find("td:last input").attr("name", "desc" + n);
                });
                
                i = i - 1;
            });
            
            return false;
        });
        
    });
    
</script>

</head>
<body>

    <font color="red">${message }</font>
    <br><br>

    
    <form action="fileuploadservlet" method="post" enctype="multipart/form-data">
        
        <table>
            <tr class="file">
                <td>File1:</td>
                <td><input type="file" name="file1"/></td>
            </tr>
            <tr class="desc">
                <td>Desc1:</td>
                <td><input type="text" name="desc1"/></td>
            </tr>
            
            <tr>
                <td><input type="submit" id="submit" value="提交"/></td>
                <td><button id="addFile">新增一个附件</button></td>
            </tr>
        </table>
        
    </form>

</body>
</html>
upload.jsp   app
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <servlet>
    <servlet-name>UploadServlet</servlet-name>
    <servlet-class>com.atguigu.fileupload.servlet.UploadServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>UploadServlet</servlet-name>
    <url-pattern>/uploadServlet</url-pattern>
  </servlet-mapping>
  <listener>
    <listener-class>
      org.apache.commons.fileupload.servlet.FileCleanerCleanup
    </listener-class>
  </listener>
  <listener>
    <listener-class>com.atguigu.fileupload.app.listener.FileUploadAppListener</listener-class>
  </listener>
  <servlet>
    <description></description>
    <display-name>FileUploadServlet</display-name>
    <servlet-name>FileUploadServlet</servlet-name>
    <servlet-class>com.atguigu.fileupload.app.servlet.FileUploadServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>FileUploadServlet</servlet-name>
    <url-pattern>/app/fileuploadservlet</url-pattern>
  </servlet-mapping>
  <servlet>
    <description></description>
    <display-name>DownloadServlet</display-name>
    <servlet-name>DownloadServlet</servlet-name>
    <servlet-class>com.atguigu.download.servlet.DownloadServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>DownloadServlet</servlet-name>
    <url-pattern>/downloadServlet</url-pattern>
  </servlet-mapping>
</web-app>
web.xml
<%@ 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=UTF-8">
<title>Insert title here</title>
</head>
<body>
    
    <!-- 静态下载 -->
    <a href="xyz.txt">download xyz.txt</a>
    
    <br>
    <br>
    
    <a href="test.jsp">download test.jsp</a>
    
    <br>
    <br>
    
    <a href="downloadServlet">DownLoad abcd.pptx</a>
    
</body>
</html>
dowload.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=UTF-8">
<title>Insert title here</title>
</head>
<body>
    
    <a href="upload.jsp">文件的上传</a>
    <br>
    <br>
    
    <a href="download.jsp">文件的下载</a>
    
</body>
</html>
index.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=UTF-8">
<title>Insert title here</title>
</head>
<body>
    
    <form action="uploadServlet" method="post" enctype="multipart/form-data">
        
        File: <input type="file" name="file"/>
        <br>
        <br>
        Desc: <input type="text" name="desc"/>
        <br>
        <br>
        
        <input type="checkbox" name="interesting" value="Reading"/>Reading
        <input type="checkbox" name="interesting" value="Party"/>Party
        <input type="checkbox" name="interesting" value="Sports"/>Sports
        <input type="checkbox" name="interesting" value="Shopping"/>Shopping
        <br>
        <br>
        
        
        <input type="submit" value="Submit"/>
        
    </form>
    
</body>
</html>
upload.jsp
<%@page import="java.util.Date"%>
<%@ 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=UTF-8">
<title>Insert title here</title>
</head>
<body>

    <% 
        //1. 通知客户端浏览器: 这是一个需要下载的文件, 不能再按普通的 html 的方式打开.
        //即设置一个响应的类型: application/x-msdownload
        response.setContentType("application/x-msdownload"); 
    
        //2. 通知客户端浏览器: 不再有浏览器来处理该文件, 而是交由用户自行处理
        //设置用户处理的方式: 响应头: Content-Disposition
        response.setHeader("Content-Disposition", "attachment;filename=abc.txt");
    %>
    
    <h4>Test Page</h4>
    
    Time: <%= new Date() %>
    
</body>
</html>
test.jsp

 

posted @ 2018-01-18 09:51  周无极  阅读(271)  评论(0编辑  收藏  举报