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

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

PHP教程|ASP.NET教程|JAVA教程|ASP教程|

服務器之家 - 編程語言 - JAVA教程 - java基于servlet編寫上傳下載功能 類似文件服務器

java基于servlet編寫上傳下載功能 類似文件服務器

2020-05-25 12:12yunsyz JAVA教程

這篇文章主要介紹了java基于servlet編寫上傳下載功能,類似文件服務器,感興趣的小伙伴們可以參考一下

本人閑來無事,寫了個servlet,實現上傳下載功能。啟動服務后,可以在一個局域網內當一個小小的文件服務器。 

一、準備工作
下載兩個jar包: 

commons-fileupload-1.3.1.jar
commons-io-2.2.jar 

二、創建一個web工程
我的工程名叫:z-upload 

三、配置web.xml

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="http://java.sun.com/xml/ns/javaee"
 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">
 <display-name>z-upload</display-name>
 <servlet>
 <servlet-name>UploadService</servlet-name>
 <servlet-class>com.syz.servlet.UploadService</servlet-class>
 </servlet>
 <servlet-mapping>
 <servlet-name>UploadService</servlet-name>
 <url-pattern>/*</url-pattern>
 </servlet-mapping>
</web-app>

 從以上配置可以看出,我的servlet類是UploadService,匹配的url是/*,意思是匹配所有訪問url。 

四、寫servlet類

?
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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
package com.syz.servlet;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
 
import javax.servlet.ServletContext;
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.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
 
 
public class UploadService extends HttpServlet {
 
  public static final String LIST = "/list";
 
  public static final String FORM = "/form";
 
  public static final String HANDLE = "/handle";
 
  public static final String DOWNLOAD = "/download";
 
  public static final String DELETE = "/delete";
 
  public static final String UPLOAD_DIR = "/upload";
 
  private static final long serialVersionUID = 2170797039752860765L;
 
  public void execute(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    System.out.println("execute...");
    System.out.println("------------begin---------------");
    req.setCharacterEncoding("UTF-8");
    String host = req.getRemoteHost();
    System.out.println("host:" + host);
    String uri = req.getRequestURI();
    System.out.println("uri:" + uri);
    ServletContext servletContext = this.getServletConfig()
        .getServletContext();
    // 上傳文件的基本路徑
    String basePath = servletContext.getRealPath(UPLOAD_DIR);
    // 上下文路徑
    String contextPath = servletContext.getContextPath();
    System.out.println("contextPath:" + contextPath);
    // 截取上下文之后的路徑
    String action = uri.substring(contextPath.length());
    System.out.println("action:" + action);
    // 依據action不同進行不同的處理
    if (action.equals(FORM)) {
      form(contextPath, resp);
    }
    else if (action.equals(HANDLE)) {
      boolean isMultipart = ServletFileUpload.isMultipartContent(req);
      System.out.println("isMultipart:" + isMultipart);
      if (!isMultipart) {
        return;
      }
      DiskFileItemFactory factory = new DiskFileItemFactory();
      File repository = (File) servletContext
          .getAttribute(ServletContext.TEMPDIR);
      System.out.println("repository:" + repository.getAbsolutePath());
      System.out.println("basePath:" + basePath);
      factory.setSizeThreshold(1024 * 100);
      factory.setRepository(repository);
      ServletFileUpload upload = new ServletFileUpload(factory);
      // 創建監聽
      ProgressListener progressListener = new ProgressListener() {
        public void update(long pBytesRead, long pContentLength,
            int pItems) {
          System.out.println("當前文件大小:" + pContentLength + "\t已經處理:"
              + pBytesRead);
        }
      };
      upload.setProgressListener(progressListener);
      List<FileItem> items = null;
      try {
        items = upload.parseRequest(req);
        System.out.println("items size:" + items.size());
        Iterator<FileItem> ite = items.iterator();
        while(ite.hasNext()){
          FileItem item = ite.next();
          if(item.isFormField()){
            // handle FormField
          }else{
            // handle file
            String fieldName = item.getFieldName();
            String fileName = item.getName();
            fileName = fileName.substring(
                fileName.lastIndexOf(File.separator) + 1);
            String contentType = item.getContentType();
            boolean isInMemory = item.isInMemory();
            long sizeInBytes = item.getSize();
            System.out.println(fieldName + "\t" + fileName + "\t"
                + contentType + "\t" + isInMemory + "\t"
                + sizeInBytes);
            File file = new File(
                basePath + "/" + fileName + "_" + getSuffix());
            // item.write(file);
            InputStream in = item.getInputStream();
            OutputStream out = new FileOutputStream(file);
            byte[] b = new byte[1024];
            int n = 0;
            while ((n = in.read(b)) != -1) {
              out.write(b, 0, n);
            }
            out.flush();
            in.close();
            out.close();
          }
        }
        // 處理完后重定向到文件列表頁面
        String href1 = contextPath + LIST;
        resp.sendRedirect(href1);
      }
      catch (FileUploadException e) {
        e.printStackTrace();
      }
      catch (Exception e) {
        e.printStackTrace();
      }
    }
    else if (action.equals(LIST)) {
      list(contextPath, basePath, resp);
    }
    else if (action.equals(DOWNLOAD)) {
      String id = req.getParameter("id");
      System.out.println("id:" + id);
      if (id == null) {
        return;
      }
      File file = new File(basePath);
      File[] list = file.listFiles();
      int len = list.length;
      boolean flag = false;
      for (int i = 0; i < len; i++) {
        File f = list[i];
        String fn = f.getName();
        if (f.isFile() && fn.lastIndexOf("_") > -1) {
          String fid = fn.substring(fn.lastIndexOf("_"));
          if (id.equals(fid)) {
            download(f, resp);
            flag = true;
            break;
          }
        }
      }
      if (!flag) {
        notfound(contextPath, resp);
      }
    }
    else if (action.equals(DELETE)) {
      String id = req.getParameter("id");
      System.out.println("id:" + id);
      if (id == null) {
        return;
      }
      File file = new File(basePath);
      File[] list = file.listFiles();
      int len = list.length;
      boolean flag = false;
      for (int i = 0; i < len; i++) {
        File f = list[i];
        String fn = f.getName();
        if (f.isFile() && fn.lastIndexOf("_") > -1) {
          String fid = fn.substring(fn.lastIndexOf("_"));
          if (id.equals(fid)) {
            f.delete();
            flag = true;
            break;
          }
        }
      }
      if (flag) {
        // 處理完后重定向到文件列表頁面
        String href1 = contextPath + LIST;
        resp.sendRedirect(href1);
      }
      else {
        notfound(contextPath, resp);
      }
    }
    else {
      show404(contextPath, resp);
    }
    System.out.println("------------end---------------");
  }
 
  private void show404(String contextPath, HttpServletResponse resp)
      throws IOException {
    resp.setContentType("text/html;charset=utf-8");
    PrintWriter out = resp.getWriter();
    String href1 = contextPath + LIST;
    out.write("<html>");
    out.write("<head><title>404</title></thead>");
    out.write("<body>");
    out.write("<b>您所訪問的頁面不存在!<a href='" + href1 + "'>點擊</a>返回文件列表</b>");
    out.write("</body>");
    out.write("</html>");
    out.close();
  }
 
  private void form(String contextPath, HttpServletResponse resp)
      throws IOException {
    resp.setContentType("text/html;charset=utf-8");
    PrintWriter out = resp.getWriter();
    String href1 = contextPath + LIST;
    out.write("<html>");
    out.write("<head><title>form</title></thead>");
    out.write("<body>");
    out.write("<b><a href='" + href1 + "'>點擊</a>返回文件列表</b>");
    out.write(
        "<form action='handle' method='post' enctype='multipart/form-data' style='margin-top:20px;'>");
    out.write("<input name='file' type='file'/><br>");
    out.write("<input type='submit' value='上傳'/><br>");
    out.write("</form>");
    out.write("</body>");
    out.write("</html>");
    out.close();
  }
 
  private void notfound(String contextPath, HttpServletResponse resp)
      throws IOException {
    resp.setContentType("text/html;charset=utf-8");
    PrintWriter out = resp.getWriter();
    String href1 = contextPath + LIST;
    out.write("<html><body><b>操作失敗!文件不存在或文件已經被刪除!<a href='" + href1
        + "'>點擊</a>返回文件列表</b></body></html>");
    out.close();
  }
 
  private void download(File f, HttpServletResponse resp)
      throws IOException {
    String fn = f.getName();
    String fileName = fn.substring(0, fn.lastIndexOf("_"));
    System.out.println("fileName:" + fileName);
    resp.reset();
    resp.setContentType("application/octet-stream");
    String encodingFilename = new String(fileName.getBytes("GBK"),
        "ISO8859-1");
    System.out.println("encodingFilename:" + encodingFilename);
    resp.setHeader("content-disposition",
        "attachment;filename=" + encodingFilename);
    InputStream in = new FileInputStream(f);
    OutputStream out = resp.getOutputStream();
    byte[] b = new byte[1024];
    int n = 0;
    while ((n = in.read(b)) != -1) {
      out.write(b, 0, n);
    }
    out.flush();
    in.close();
    out.close();
  }
 
  private void list(String contextPath, String basePath,
      HttpServletResponse resp)
      throws IOException {
    String href_u = contextPath + FORM;
    resp.setContentType("text/html;charset=utf-8");
    PrintWriter out = resp.getWriter();
    out.write("<html>");
    out.write("<head><title>list</title></thead>");
    out.write("<body>");
    out.write("<b>我要<a href='" + href_u + "'>上傳</a></b><br>");
    out.write(
        "<table border='1' style='border-collapse:collapse;width:100%;margin-top:20px;'>");
    out.write("<thead>");
    out.write("<tr>");
    out.write("<th>序號</th><th>文件名</th><th>操作</th>");
    out.write("</tr>");
    out.write("</thead>");
    out.write("<tbody>");
    File file = new File(basePath);
    File[] list = file.listFiles();
    System.out
        .println("basePath:" + basePath + "\tlist.size:" + list.length);
    int len = list.length;
    int no = 1;
    for (int i = 0; i < len; i++) {
      File f = list[i];
      System.out.println(i + "\t" + f.getName());
      String fn = f.getName();
      if (f.isFile() && fn.lastIndexOf("_") > -1) {
        String filename = fn.substring(0, fn.lastIndexOf("_"));
        String id = fn.substring(fn.lastIndexOf("_"));
        String href1 = contextPath + DOWNLOAD + "?id=" + id;
        String href2 = contextPath + DELETE + "?id=" + id;
        StringBuilder sb = new StringBuilder();
        sb.append("<tr>");
        sb.append("<td>");
        sb.append(no++);
        sb.append("</td>");
        sb.append("<td>");
        sb.append(filename);
        sb.append("</td>");
        sb.append("<td>");
        sb.append("<a href='");
        sb.append(href1);
        sb.append("'>下載</a> <a href='");
        sb.append(href2);
        sb.append("' onclick='return confirm(\"您確定要刪除嗎?\");'>刪除</a>");
        sb.append("</td>");
        sb.append("</tr>");
        out.write(sb.toString());
      }
    }
    out.write("</tbody>");
    out.write("</table>");
    out.write("</body>");
    out.write("</html>");
    out.close();
  }
 
  public void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    System.out.println("doGet...");
    execute(req, resp);
  }
 
  public void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    System.out.println("doPost...");
    execute(req, resp);
  }
 
  private String getSuffix() {
    Date date = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
    String suffix = sdf.format(date);
    return suffix;
  }
}

其實UploadService類可以直接實現service方法,而不用實現doGet、doPost方法。

以上servlet我也不想多解釋什么,自己看代碼吧。

五、效果圖

1.項目結構圖

java基于servlet編寫上傳下載功能 類似文件服務器

2.404頁面

java基于servlet編寫上傳下載功能 類似文件服務器

/*會匹配所有包括空字符,所以圖片中的路徑會匹配,在UploadService中的if判斷中出現在else中,因為此時的action是空字符。

3.文件列表頁面

java基于servlet編寫上傳下載功能 類似文件服務器

4.上傳表單頁面

java基于servlet編寫上傳下載功能 類似文件服務器

5.下載

java基于servlet編寫上傳下載功能 類似文件服務器

6.刪除

java基于servlet編寫上傳下載功能 類似文件服務器

7.文件找不到,如果你點刪除時,文件在服務器上已經不存在,那么會進入此頁面

java基于servlet編寫上傳下載功能 類似文件服務器

8.打包的源碼工程和war包

java基于servlet編寫上傳下載功能 類似文件服務器

其中z-upload是eclipse源碼工程,z-upload.war是打好的war包

全工程就兩個jar包,一個web.xml和一個servlet類,可以自己從文章中拷貝過去測試一下,如果是懶人,可以下載

http://download.csdn.net/detail/yunsyz/9569680,特別提醒,下載要1分哦。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 77成人影视 | 女子监狱第二季在线观看免费完整版 | 国产日韩欧美一区 | 亚洲剧情在线 | 村上里沙40分钟在线观看 | 91精品免费国产高清在线 | 手机在线观看网站免费视频 | 日韩中文字幕视频在线观看 | 国内自拍网红在线综合 | 99久久国产综合精麻豆 | 国产国语videosex另类 | 国产伦精品一区二区三区女 | 海角社区在线登录 | 亚洲va欧美va国产综合久久 | 国产亚洲女人久久久久久 | 含羞草国产亚洲精品岁国产精品 | 欧美高清在线精品一区 | 国产免费一区不卡在线 | 希岛爱理作品在线观看 | 和老外3p爽粗大免费视频 | 国产日韩欧美色视频色在线观看 | 日韩欧免费一区二区三区 | 久9视频这里只有精品123 | 艾秋麻豆果冻传媒老狼仙踪林 | 亚洲色图欧美图片 | 麻麻与子乱肉小说怀孕 | 日麻逼 | 国产裸露片段精华合集链接 | 国产在线麻豆波多野结衣 | 花房乱爱在线观看 | 亚洲成人黄色 | 特黄特a级特别特级特毛片 特黄a级三级三级野战 | 国产男技师 | 四虎影视永久在线 | 黑人biglackon10十 | 精品一区二区免费视频蜜桃网 | 日韩综合第一页 | 成年女人毛片免费观看中文w | 99久久精品免费精品国产 | 我被黑人彻底征服的全文 | 国产精品每日在线观看男人的天堂 |