zoukankan      html  css  js  c++  java
  • java实现文件上传下载

    喜欢的朋友可以关注下,粉丝也缺。

    今天发现已经有很久没有给大家分享一篇技术文章了,于是想了一下给大家分享一篇java实现文件上传下载功能的文章,不喜欢的希望大家勿喷。

    想必大家都知道文件的上传前端页面是需要用表单来提交,下面我就直接贴代码:

    <div style="margin-bottom:5px" id="wjid">  
                <form action="/automaticffice/SmartUploadServlet" method="post"    
                    enctype="multipart/form-data">    
                    <input id="filename" name="filename" type="file"    
                         /> <input type="submit" class="easyui-linkbutton" icon="icon-ok" value="提 交" /><span style="color: red">${message}</span>  
                </form>    
    </div> 
    

      

      下面我们来说说后台的代码应该怎么写,这里我是用了 jspSmartUpload.jar 这个包,使用非常的方便,这里我提供一个下载地址给大家

    https://download.csdn.net/download/dsn727455218/10422388

      还是直接上代码:

      

    @WebServlet("/SmartUploadServlet")  
    public class SmartUploadServlet extends HttpServlet {  
        private static final long serialVersionUID = 1L;  
        private Connection conn;  
        private PreparedStatement pst;  
      
        /** 
         * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse 
         *      response) 
         */  
        protected void doGet(HttpServletRequest request, HttpServletResponse response)  
                throws ServletException, IOException {  
            request.setCharacterEncoding("UTF-8");  
            response.setCharacterEncoding("UTF-8");  
            response.setContentType("text/html;charset=UTF-8");  
            // 设置上传的保存路径  
            String filePath = getServletContext().getRealPath("/") + "\upload\";  
            System.err.println(filePath);  
            // 创建文件对象 如果存在就不创建,否则创建文件夹  
            File file = new File(filePath);  
            if (file.exists()) {  
                file.mkdir();  
            }  
            // 创建SmartUpload对象  
            SmartUpload su = new SmartUpload();  
            // 初始化对象  
            su.initialize(getServletConfig(), request, response);  
            // 设置上传文件大小  
            su.setTotalMaxFileSize(1024 * 1024 * 100);  
            // 设置上传文件类型  
            //        su.setAllowedFilesList("txt,jpg,gif,xls,doc,docx");  
            // 创建提示变量  
            String result = "上传成功";  
            try {  
                // 设置禁止上传类型  
                //            su.setDeniedFilesList("rar,jsp,js");  
                su.upload();  
                // 返回上传文件数量  
                int count = su.save(filePath);  
                System.out.println("上传成功" + count + "个文件!");  
      
            } catch (Exception e) {  
                result = "上传失败";  
                e.printStackTrace();  
            }  
      
            // 获取上传成功的文件的属性  
            for (int i = 0; i < su.getFiles().getCount(); i++) {  
                com.jspsmart.upload.File tempFile = su.getFiles().getFile(i);  
                System.out.println("---------------------");  
                System.out.println("表单当中name属性值:" + tempFile.getFieldName());  
                System.out.println("上传文件名:" + tempFile.getFieldName());  
                System.out.println("上传文件长度:" + tempFile.getSize());  
                System.out.println("上传文件的拓展名:" + tempFile.getFileExt());  
                System.out.println("上传文件的全名:" + tempFile.getFilePathName());  
                System.out.println("---------------------");  
                
            }  
            request.setAttribute("message", result);  
      
            RequestDispatcher dispatcher = request.getRequestDispatcher("do/wenjian.jsp");  
            dispatcher.forward(request, response);  
        }  
      
        /** 
         * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse 
         *      response) 
         */  
        protected void doPost(HttpServletRequest request, HttpServletResponse response)  
                throws ServletException, IOException {  
            // TODO Auto-generated method stub  
            doGet(request, response);  
        }  
      
    }  

      

      其实上传文件就是这么的简单,下面我们来说说文件的下载,相信很多的朋友有遇到过文件名字为中文的文件就无法下载的问题,接下来我们就详细的来说下这个问题:

    同样的前端还是要以表单的方式提交:

    input里面value的值是你需要下载文件的名字,action都知道是servetl的路径了

      

    <form action="/automaticffice/BatchDownloadServlet"> <input type="hidden" name="filename" value="' + cellvalue + '"/> <input type="submit" value="下载文件"/></form> 

      在servlet中如何接收处理:

      

    @WebServlet("/BatchDownloadServlet")  
    public class BatchDownloadServlet 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 {  
      
            String name = request.getParameter("filename");  
            /** 
             * 这里是重点,如何解决文件名为中文的问题,不同的浏览器处理的方式会有所不同 
             * IE的话,通过URLEncoder对filename进行UTF8编码, 
             * 而其他的浏览器(firefox、chrome、safari、opera),则要通过字节转换成ISO8859-1了 
             * 所以这里我们需要判断一下使用的是什么浏览器 在根据浏览器来做相应的编码 
             */  
            if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {  
                name = URLEncoder.encode(name, "UTF-8");  
            } else {  
                name = new String(name.getBytes(), "ISO-8859-1");  
            }  
            response.setContentType("application/octet-stream");  
            // 以附件的形式下载  
            response.setHeader("Content-Disposition", "attachment;filename="" + name + """);  
      
            // 获取下载路径  
            String path = getServletContext().getRealPath("/") + "\upload\";  
            // 获取文件数组  
            String[] filenames = request.getParameterValues("filename");  
            // 创建空字符串  
            String str = "";  
            // 换行符  
            String rt = "
    ";  
            // 创建压缩包输出流  
            ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());  
            // 遍历文件数组  
            for (String filename : filenames) {  
                str += filename + rt;  
                // 创建文件对象  
                File file = new File(path + filename);  
                zos.putNextEntry(new ZipEntry(filename));  
                // 创建文件输出流  
                FileInputStream fis = new FileInputStream(file);  
                byte[] b = new byte[1024];  
                int n = 0;  
                while ((n = fis.read(b)) != -1) {  
                    zos.write(b, 0, n);  
                }  
                zos.flush();  
                fis.close();  
            }  
            zos.setComment("成功" + rt + str);  
            zos.flush();  
            zos.close();  
        }  
      
        /** 
         * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse 
         *      response) 
         */  
        protected void doPost(HttpServletRequest request, HttpServletResponse response)  
                throws ServletException, IOException {  
            // TODO Auto-generated method stub  
            doGet(request, response);  
        }  
      
    }  

    到这里已经完成了对文件的上传下载功能,如有需要可以加我Q群【308742428】大家一起讨论技术

    下一篇我将继续为大家分享 如何实现文件的在线预览功能,希望大家期待

    喜欢的朋友可以关注下,粉丝也缺。

  • 相关阅读:
    利用智能手机(Android)追踪一块磁铁(三)
    利用智能手机(Android)追踪一块磁铁(二)
    利用智能手机(Android)追踪一块磁铁(一)
    android音频发生器
    接口的作用(java)
    Botposter.com集群ETCD2.3.7升级至3.0实录[原创]
    springboot2+jpa+hikari+oracle实战
    Nginx配置详解
    Nginx安装启动+springboot项目实现负载均衡实战
    springboot使用websocket进行实时传送信息实战(包含服务端和客户端)
  • 原文地址:https://www.cnblogs.com/dsn727455218/p/9056591.html
Copyright © 2011-2022 走看看