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

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

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)就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 欧美一级在线全免费 | 欧美日韩视频在线第一区二区三区 | 18性夜影院午夜寂寞影院免费 | 黑人又大又硬又粗再深一点 | 美国xaxwaswaskino 美妇在线 | 国产美女屁股直流白浆视频无遮挡 | 国产免费又粗又猛又爽视频国产 | 久久精品男人影院 | 免费观看视频高清在线 | 欧美一级片免费在线观看 | 日产乱码卡一卡2卡三卡四福利 | 日韩专区 | 亚洲高清中文字幕一区二区三区 | 很黄的网站在线观看 | 99在线观看免费视频 | 韩国最新理论片奇忧影院 | 青青青国产手机在线播放 | 日本一区三区 | 和肥岳在厨房激情 | 日韩一区二三区无 | 国产高清专区 | 国产成人精品系列在线观看 | 久久er99热精品一区二区 | 好男人在线观看hd中字 | 欧美在线成人免费国产 | 国产成人影院 | 11 13加污女qq看他下面 | 97精品国产高清在线看入口 | 亚洲精品视频网 | 19+韩国女主播激情vip视频在线 | 亚洲国产精品嫩草影院久久 | 人人澡 人人澡碰人人看软件 | 无码一区二区三区视频 | 校花被拖到野外伦小说 | 亚洲第一在线播放 | 青青国产在线视频 | 亚洲天堂2016 | b站免费网站入口 | 色婷亚洲 | 情侣奴伺候女王第2部分小说 | 国产精品国产三级在线专区 |