java文件上传下载 使用SmartUpload组件实现

 使用SmartUpload组件实现(下载jsmartcom_zh_CN.jar) 2017-11-07  

1、在WebRoot创建以下文件夹,css存放样式文件(css文件直接拷贝进去),images存放图片(图片也拷贝进去),js存放js文件(拷贝),jsp存放我们的jsp文件

2、创建jsp文件 01.jsp

3、编写jsp

 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 2 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 3 <%
 4 String path = request.getContextPath();
 5 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 6 %>
 7 <html>
 8   <head>
 9     <base href="<%=basePath%>">
10     <title>My JSP '01.jsp' starting page</title>
11     <!-- 引入我们css样式文件 -->
12     <link rel="stylesheet" type="text/css" href="css/common.css">
13     <!-- 引入我们js文件 -->
14     <script type="text/javascript" src="js/jquery-1.11.1.js"></script>
15     <script type="text/javascript">
16         /*
17             替换默认显示图片,显示当前我们选中的图片
18             1、获取<p class="thumbs">中<a>标签事件
19             2、获取href title
20             3、获取<p><img id="largeImg"</p> 
21             4、把当前选中的href title赋给默认
22         */
23         $(function(){
24             $(".thumbs a").click(function(){
25                 var largePath = $(this).attr("href");
26                 var largeAlt = $(this).attr("title");
27                 $("#largeImg").attr({
28                     src:largePath,
29                     alt:largeAlt
30                 });
31                 return false;
32             });
33         });
34         
35     </script>
36   </head>
37   
38   <body>
39         <h2>文件批量上传</h2>
40         <!-- 处理类路径,提交方式,类型 -->
41         <form action="smartUploadServlet.do" method="post" enctype="multipart/form-data">
42             <label>文件一:</label>
43             <input name="myfile1" type="file"/><br>
44             <label>文件二:</label>
45             <input name="myfile2" type="file"/><br>
46             <label>文件三:</label>
47             <input name="myfile3" type="file"/><br>
48             <!-- 处理完后台返回一个消息同el表达式${result} -->
49             <input type="submit" value="上传文件"/><b style="color: red">${result}</b>
50         </form>
51         <hr>
52         
53         <h2>文件批量下载</h2>
54         <!-- 处理类路径 -->
55         <form action="batchDownloadServlet.do">
56             <input type="checkbox" name="filename" value="img2-lg.jpg"/>Image2
57             <input type="checkbox" name="filename" value="img3-lg.jpg"/>Image3
58             <input type="checkbox" name="filename" value="img4-lg.jpg"/>Image4
59             <input type="submit" value="下载文件"/>
60         </form>
      <!--
下载:<input type="file" name="filename" value="img2-lg.jpg"/>Image2
   --> 61 <hr> 62 63 <h2>图片预览</h2> 64 <p><img id="largeImg" alt="Large Image" src="images/img1-lg.jpg"></p> 65 <p class="thumbs"> 66 <a href="images/img2-lg.jpg" title="Image2"><img src="images/img2-thumb.jpg"></a> 67 <a href="images/img3-lg.jpg" title="Image3"><img src="images/img3-thumb.jpg"></a> 68 <a href="images/img4-lg.jpg" title="Image4"><img src="images/img4-thumb.jpg"></a> 69 <a href="images/img5-lg.jpg" title="Image5"><img src="images/img5-thumb.jpg"></a> 70 <a href="images/img6-lg.jpg" title="Image6"><img src="images/img6-thumb.jpg"></a> 71 </p> 72 </body> 73 </html>

4、后台创建SmartUploadServlet(上传)   web.xml配置路径,jsp文件中<form action="smartUploadServlet.do">必须和web.xml中一致

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 3 xmlns="http://java.sun.com/xml/ns/javaee" 
 4 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
 5   <display-name>scx</display-name>
 6   
 7   <servlet>
 8     <servlet-name>SmartUploadServlet</servlet-name>
 9     <servlet-class>com.imooc.servlet.SmartUploadServlet</servlet-class>
10   </servlet>
11   
12   <servlet>
13     <servlet-name>SmartDownloadServlet</servlet-name>
14     <servlet-class>com.imooc.servlet.SmartDownloadServlet</servlet-class>
15   </servlet>
16   <servlet>
17     <servlet-name>BatchDownloadServlet</servlet-name>
18     <servlet-class>com.imooc.servlet.BatchDownloadServlet</servlet-class>
19   </servlet>
20 
21   <servlet-mapping>
22     <servlet-name>SmartUploadServlet</servlet-name>
23     <url-pattern>/smartUploadServlet.do</url-pattern>
24   </servlet-mapping>
25   
26   <servlet-mapping>
27     <servlet-name>SmartDownloadServlet</servlet-name>
28     <url-pattern>/smartDownloadServlet.do</url-pattern>
29   </servlet-mapping>
30   
31   <servlet-mapping>
32     <servlet-name>BatchDownloadServlet</servlet-name>
33     <url-pattern>/batchDownloadServlet.do</url-pattern>
34   </servlet-mapping>
35   
36   <welcome-file-list>
37     <welcome-file>index.jsp</welcome-file>
38   </welcome-file-list>
39 </web-app>

 

5、编写SmartUploadServlet(多个上传,单个上传只需要把jsp文件中input留下一个)

 1 package com.imooc.servlet;
 2 
 3 import java.io.File;
 4 import java.io.IOException;
 5 
 6 import javax.servlet.ServletException;
 7 import javax.servlet.http.HttpServlet;
 8 import javax.servlet.http.HttpServletRequest;
 9 import javax.servlet.http.HttpServletResponse;
10 
11 import com.jspsmart.upload.SmartUpload;
12 
13 public class SmartUploadServlet extends HttpServlet {
14 
15     /**
16      * 
17      */
18     private static final long serialVersionUID = 1L;
19 
20     public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
21         doPost(req, resp);
22     }
23 
24     public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
25 
26         req.setCharacterEncoding("UTF-8");
27         // 设置上传的保存路径
28         String filePath = getServletContext().getRealPath("/") + "images";
29         // 创建文件对象 如果存在就不创建,否则创建文件夹
30         File file = new File(filePath);
31         if (file.exists()) {
32             file.mkdir();
33         }
34         // 创建SmartUpload对象
35         SmartUpload su = new SmartUpload();
36         // 初始化对象
37         su.initialize(getServletConfig(), req, resp);
38         // 设置上传文件大小
39         su.setTotalMaxFileSize(1024 * 1024 * 100);
40         // 设置上传文件类型
41         su.setAllowedFilesList("txt,jpg,gif");
42         // 创建提示变量
43         String result = "上传成功";
44         try {
45             // 设置禁止上传类型
46             su.setDeniedFilesList("rar,jsp,js");
47             su.upload();
48             // 返回上传文件数量
49             int count = su.save(filePath);
50             System.out.println("上传成功" + count + "个文件!");
51 
52         } catch (Exception e) {
53             result = "上传失败";
54             e.printStackTrace();
55         }
56 
57         // 获取上传成功的文件的属性
58         for (int i = 0; i < su.getFiles().getCount(); i++) {
59             com.jspsmart.upload.File tempFile = su.getFiles().getFile(i);
60             System.out.println("---------------------");
61             System.out.println("表单当中name属性值:" + tempFile.getFieldName());
62             System.out.println("上传文件名:" + tempFile.getFieldName());
63             System.out.println("上传文件长度:" + tempFile.getSize());
64             System.out.println("上传文件的拓展名:" + tempFile.getFileExt());
65             System.out.println("上传文件的全名:" + tempFile.getFilePathName());
66             System.out.println("---------------------");
67         }
68         req.setAttribute("result", result);
69         req.getRequestDispatcher("jsp/01.jsp").forward(req, resp);
70     }
71 
72 }

6、SmartDownloadServlet(单个下载)
 1 package com.imooc.servlet;
 2 
 3 import java.io.IOException;
 4 
 5 import javax.servlet.ServletException;
 6 import javax.servlet.http.HttpServlet;
 7 import javax.servlet.http.HttpServletRequest;
 8 import javax.servlet.http.HttpServletResponse;
 9 
10 import com.jspsmart.upload.SmartUpload;
11 import com.jspsmart.upload.SmartUploadException;
12 
13 public class SmartDownloadServlet extends HttpServlet {
14 
15     /**
16      * 
17      */
18     private static final long serialVersionUID = 1L;
19 
20     public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
21         doPost(request, response);
22     }
23 
24     public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
25         // 获取文件名称
26         String filename = request.getParameter("filename");
27         SmartUpload su = new SmartUpload();
28         // 初始化
29         su.initialize(getServletConfig(), request, response);
30         // 把默认显示方式设为空
31         su.setContentDisposition(null);
32 
33         try {
34             su.downloadFile("/images/" + filename);
35         } catch (SmartUploadException e) {
36             e.printStackTrace();
37         }
38     }
39 }
7、BatchDownloadServlet(多个文件下载)
 1 package com.imooc.servlet;
 2 
 3 import java.io.File;
 4 import java.io.FileInputStream;
 5 import java.io.IOException;
 6 import java.util.zip.ZipEntry;
 7 import java.util.zip.ZipOutputStream;
 8 
 9 import javax.servlet.ServletException;
10 import javax.servlet.http.HttpServlet;
11 import javax.servlet.http.HttpServletRequest;
12 import javax.servlet.http.HttpServletResponse;
13 
14 public class BatchDownloadServlet extends HttpServlet {
15 
16     /**
17      * 
18      */
19     private static final long serialVersionUID = 1L;
20 
21     public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
22         doPost(req, resp);
23     }
24 
25     public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
26         resp.setContentType("application/x-msdownload");
27         // 以附件的形式下载
28         resp.setHeader("Content-Disposition", "attachment;filename=test.zip");
29 
30         // 获取下载路径
31         String path = getServletContext().getRealPath("/") + "images/";
32         // 获取文件数组
33         String[] filenames = req.getParameterValues("filename");
34         // 创建空字符串
35         String str = "";
36         // 换行符
37         String rt = "\r\n";
38         // 创建压缩包输出流
39         ZipOutputStream zos = new ZipOutputStream(resp.getOutputStream());
40         // 遍历文件数组
41         for (String filename : filenames) {
42             str += filename + rt;
43             // 创建文件对象
44             File file = new File(path + filename);
45             zos.putNextEntry(new ZipEntry(filename));
46             // 创建文件输出流
47             FileInputStream fis = new FileInputStream(file);
48             byte[] b = new byte[1024];
49             int n = 0;
50             while ((n = fis.read(b)) != -1) {
51                 zos.write(b, 0, n);
52             }
53             zos.flush();
54             fis.close();
55         }
56         zos.setComment("成功" + rt + str);
57         zos.flush();
58         zos.close();
59     }
60 }

效果图
 
   

 

 

 

 

转载于:https://www.cnblogs.com/haha66/p/7798395.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值