zoukankan      html  css  js  c++  java
  • JavaWeb(九):上传和下载

    表单

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

    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>

    会自动生成一个输入框和一个按钮,输入框可供用户填写本地文件的文件名和路径名,按钮可以让浏览器打开一个文件选择框供用户选择文件:

    4). 关于 enctype:

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

    > multipart/form-data:form 设定了enctype=“multipart/form-data”属性后,表示表单以二进制传输数据

    服务端

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

        <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="submit" value="Submit" />
        </form>

    Servlet

    public class UploadServlet extends HttpServlet{
    
        private static final long serialVersionUID = 1L;
        
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            // 1. 获取请求信息
            String file = req.getParameter("file");
            
        }
    }

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

    package com.aidata.web;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.Reader;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class UploadServlet extends HttpServlet {
    
        private static final long serialVersionUID = 1L;
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
            InputStream in = req.getInputStream();
    
            Reader reader = new InputStreamReader(in);
            BufferedReader bufferedReader = new BufferedReader(reader);
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                System.out.println(str);
            }
        }
    }

    使用 commons-fileupload 组件

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

    搭建环境

    加入 jar包
    commons-fileupload-1.2.1.jar
    commons-io-2.0.jar

    基本思想:

    > 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();
    }

    如何得到 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);

    下面是简单的上传Servlet

    package com.aidata.web;
    
    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();
    
                        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);
    
                        InputStream in = item.getInputStream();
                        byte[] buffer = new byte[1024];
                        int len = 0;
    
                        fileName = "d:\files\" + fileName;
                        System.out.println(fileName);
    
                        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();
            }
    
        }
    
    }

    案例

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

    1). 需求:

    上传

    > 在 upload.jsp 页面上使用 jQuery 实现 "新增一个附件","删除附件",但至少需要保留一个.。

    <%@ 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>

    > 对文件的扩展名和文件的大小进行验证。 以下的规则是可配置的,而不是写死在程序中的。

    • >> 文件的扩展名必须为 pptx, docx, doc
    • >> 每个文件的大小不能超过 1 M
    • >> 总的文件大小不能超过 5 M.

    upload.properties

    exts=pptx,docx,doc
    file.max.size=1048576
    total.file.max.size=5242880
    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
        }
        
    }
    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);
        }
        
    }


    > 若验证失败, 则在 upload.jsp 页面上显示错误消息:

    • >> 若某一个文件不符合要求: xxx 文件扩展名不合法 或 xxx 文件大小超过 1 M
    • >> 总的文件大小不能超过 5 M.


    > 若验证通过, 则进行文件的上传操作

    • >> 文件上传, 并给一个不能和其他文件重复的名字, 但扩展名不变
    • >> 在对应的数据表中添加一条记录.

          id file_name file_path file_desc

    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
        }
    }
    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;
        }
    
    }
    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("");
            }
        }
        
    }
    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;
        }
        
    }
    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);
            }
            
        }
        
    }
    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);
        }
    }

    下载

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

    文件的下载:

    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();
    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 = "文件下载.pptx";
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            
            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();
        }
    
    }
  • 相关阅读:
    python学习
    androidandroid中的通过网页链接打开本地app
    Android自定义View之绘制虚线
    Backbone学习记录(3)
    Backbone学习记录(2)
    Backbone学习记录(1)
    网络时间轴中竖线的含义
    控制台笔记
    css hack 笔记
    Fiddler学习笔记
  • 原文地址:https://www.cnblogs.com/aidata/p/12013493.html
Copyright © 2011-2022 走看看