一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - Java教程 - Java Servlet簡單實例分享(文件上傳下載demo)

Java Servlet簡單實例分享(文件上傳下載demo)

2020-11-02 17:39Java教程網 Java教程

下面小編就為大家帶來一篇Java Servlet簡單實例分享(文件上傳下載demo)。小編覺得挺不錯的,現在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

項目結構

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
src
  com
    servletdemo
        DownloadServlet.java
        ShowServlet.java
        UploadServlet.java
        
WebContent
  jsp
    servlet
        download.html
        fileupload.jsp
        input.jsp
        
  WEB-INF
    lib
        commons-fileupload-1.3.1.jar
        commons-io-2.4.jar

1.簡單實例

ShowServlet.java

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package com.servletdemo;
 
import java.io.IOException;
import java.io.PrintWriter;
 
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
/**
 * Servlet implementation class ShowServlet
 */
@WebServlet("/ShowServlet")
public class ShowServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;
  PrintWriter pw=null
  /**
   * @see HttpServlet#HttpServlet()
   */
  public ShowServlet() {
    super();
    // TODO Auto-generated constructor stub
  }
 
  /**
   * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    this.doPost(request, response);
  }
 
  /**
   * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    request.setCharacterEncoding("gb2312");
    response.setContentType("text/html;charset=gb2312");
    pw=response.getWriter();
    String name=request.getParameter("username");
    String password=request.getParameter("password");
    pw.println("user name:" + name);
    pw.println("<br>");
    pw.println("user password:" + password);
  }
 
}

input.jsp

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
  pageEncoding="ISO-8859-1"%>
<!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>servlet demo</title>
</head>
<body>
<form action="<%=request.getContextPath()%>/ShowServlet">
    <table>
      <tr>
        <td>name</td>
        <td><input type="text" name="username"></td>
      </tr>
      <tr>
        <td>password</td>
        <td><input type="text" name="password"></td>
      </tr>
      <tr>
        <td><input type="submit" value="login"></td>
        <td><input type="reset" value="cancel"></td>
      </tr>
    </table>
  </form>
</body>
</html>

2.文件上傳實例

UploadServlet.java

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
package com.servletdemo;
 
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;
 
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
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.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
 * Servlet implementation class UploadServlet
 */
@WebServlet("/servlet/UploadServlet")
public class UploadServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;
    
  /**
   * @see HttpServlet#HttpServlet()
   */
  public UploadServlet() {
    super();
    // TODO Auto-generated constructor stub
  }
 
  /**
   * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    //設置編碼
    request.setCharacterEncoding("UTF-8");
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter pw = response.getWriter();
    try {
      //設置系統環境
      DiskFileItemFactory factory = new DiskFileItemFactory();
      //文件存儲的路徑
      String storePath = getServletContext().getRealPath("/WEB-INF/files");
      //判斷傳輸方式 form enctype=multipart/form-data
      boolean isMultipart = ServletFileUpload.isMultipartContent(request);
      if(!isMultipart)
      {
        pw.write("傳輸方式有錯誤!");
        return;
      }
      ServletFileUpload upload = new ServletFileUpload(factory);
      upload.setFileSizeMax(4*1024*1024);//設置單個文件大小不能超過4M
      upload.setSizeMax(4*1024*1024);//設置總文件上傳大小不能超過6M
      //監聽上傳進度
      upload.setProgressListener(new ProgressListener() {
 
        //pBytesRead:當前以讀取到的字節數
        //pContentLength:文件的長度
        //pItems:第幾項
        public void update(long pBytesRead, long pContentLength,
            int pItems) {
          System.out.println("已讀去文件字節 :"+pBytesRead+" 文件總長度:"+pContentLength+"  第"+pItems+"項");
           
        }
      });
      //解析
      List<FileItem> items = upload.parseRequest(request);
      for(FileItem item: items)
      {
        if(item.isFormField())//普通字段,表單提交過來的
        {
          String name = item.getFieldName();
          String value = item.getString("UTF-8");
          System.out.println(name+"=="+value);
        }else
        {
//         String mimeType = item.getContentType(); 獲取上傳文件類型
//         if(mimeType.startsWith("image")){
          InputStream in =item.getInputStream();
          String fileName = item.getName(); 
          if(fileName==null || "".equals(fileName.trim()))
          {
            continue;
          }
          fileName = fileName.substring(fileName.lastIndexOf("\\")+1);
          fileName = UUID.randomUUID()+"_"+fileName;
           
          //按日期來建文件夾
          String newStorePath = makeStorePath(storePath);
          String storeFile = newStorePath+"\\"+fileName;
          OutputStream out = new FileOutputStream(storeFile);
          byte[] b = new byte[1024];
          int len = -1;
          while((len = in.read(b))!=-1)
          {
             out.write(b,0,len);    
          }
          in.close();
          out.close();
          item.delete();//刪除臨時文件
        }
       }
//     }
    }catch(org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException e){ 
       //單個文件超出異常
      pw.write("單個文件不能超過4M");
    }catch(org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException e){
      //總文件超出異常
      pw.write("總文件不能超過6M");
       
    }catch (FileUploadException e) {
      e.printStackTrace();
    }
  }
 
  /**
   * @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);
  }
  
  private String makeStorePath(String storePath) {
    
    Date date = new Date();
    DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM);
    String s = df.format(date);
    String path = storePath+"\\"+s;
    File file = new File(path);
    if(!file.exists())
    {
      file.mkdirs();//創建多級目錄,mkdir只創建一級目錄
    }
    return path;
      
  }
  private String makeStorePath2(String storePath, String fileName) {
    int hashCode = fileName.hashCode();
    int dir1 = hashCode & 0xf;// 0000~1111:整數0~15共16個
    int dir2 = (hashCode & 0xf0) >> 4;// 0000~1111:整數0~15共16個
   
    String path = storePath + "\\" + dir1 + "\\" + dir2; // WEB-INF/files/1/12
    File file = new File(path);
    if (!file.exists())
      file.mkdirs();
   
    return path;
  }
 
}

fileupload.jsp

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
  pageEncoding="ISO-8859-1"%>
 
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
 
<!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>Upload File Demo</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/servlet/UploadServlet" method="post" enctype="multipart/form-data">
  user name<input type="text" name="username"/> <br/>
  <input type="file" name="f1"/><br/>
  <input type="file" name="f2"/><br/>
  <input type="submit" value="save"/>
 </form>
</body>
</html>

3.文件下載實例

DownloadServlet.java

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package com.servletdemo;
 
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
 
 
 
import java.net.URLEncoder;
 
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletResponse;
 
/**
 * Servlet implementation class DownloadServlet
 */
@WebServlet("/DownloadServlet")
public class DownloadServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;
    
  /**
   * @see HttpServlet#HttpServlet()
   */
  public DownloadServlet() {
    super();
    // TODO Auto-generated constructor stub
  }
 
  /**
   * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    download1(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);
  }
  
  public void download1(HttpServletResponse response) throws IOException{
    //獲取所要下載文件的路徑
     String path = this.getServletContext().getRealPath("/files/web配置.xml");
     String realPath = path.substring(path.lastIndexOf("\\")+1);
   
     //告訴瀏覽器是以下載的方法獲取到資源
     //告訴瀏覽器以此種編碼來解析URLEncoder.encode(realPath, "utf-8"))
    response.setHeader("content-disposition","attachment; filename="+URLEncoder.encode(realPath, "utf-8"));
    //獲取到所下載的資源
     FileInputStream fis = new FileInputStream(path);
     int len = 0;
      byte [] buf = new byte[1024];
      while((len=fis.read(buf))!=-1){
        response.getOutputStream().write(buf,0,len);
      }
   }
 
}

download.html

?
1
2
3
4
5
6
7
8
9
10
11
12
13
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Download Demo</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
<a href = "/JavabeanDemo/DownloadServlet">download</a>
</body>
</html>

以上這篇Java Servlet簡單實例分享(文件上傳下載demo)就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 99这里只有精品在线 | 顶级欧美做受xxx000 | 动漫jk美女被爆羞羞漫画 | 欧美人shou交在线播放 | 欧美a在线观看 | 粉嫩尤物在线456 | 男人把j放进女人的p里视频 | 国产成人一级 | 91精品国产亚洲爽啪在线影院 | 5g影院天天 | 青青草原国产视频 | 色老板最新网站视频地址 | 高清国语自产拍免费视频国产 | 加勒比一本大道香蕉在线视频 | 暖暖视频免费观看视频中国.韩剧 | 无人在线高清观看 | 四虎国产精品视频免费看 | 色戒真做gif动图 | 色视频国产| 亚洲国产成人精品不卡青青草原 | 四虎精品永久免费 | 欧美日韩1区 | 精品国产自在现线拍国语 | 日韩欧美亚洲每日更新网 | 无码精品一区二区三区免费视频 | 久久精品亚洲热综合一本 | 免费成年视频 | 日本热妇 | www.亚洲色图 | 5g影院成人 | 五月天中文在线 | 亚洲国产精品久久久久 | 美女伊人网 | 调教校花浣肠开菊 | 日本午夜vr影院新入口 | 日韩精品免费一区二区 | 不良小说| 亚洲成人精品久久 | 久久亚洲成a人片 | 日本高清视频在线的 | 日本捏胸吃奶视频免费 |