最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

 更新時(shí)間:2021年03月23日 09:02:37   作者:yunsyz  
這篇文章主要為大家詳細(xì)介紹了java基于servlet編寫上傳下載功能,類似文件服務(wù)器,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

本人閑來(lái)無(wú)事,寫了個(gè)servlet,實(shí)現(xiàn)上傳下載功能。啟動(dòng)服務(wù)后,可以在一個(gè)局域網(wǎng)內(nèi)當(dāng)一個(gè)小小的文件服務(wù)器。

一、準(zhǔn)備工作

下載兩個(gè)jar包: 

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

二、創(chuàng)建一個(gè)web工程

我的工程名叫:z-upload 

三、配置web.xml

 <?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是/*,意思是匹配所有訪問(wèn)url。 

四、寫servlet類

 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);
  // 依據(jù)action不同進(jìn)行不同的處理
  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);
   // 創(chuàng)建監(jiān)聽
   ProgressListener progressListener = new ProgressListener() {
    public void update(long pBytesRead, long pContentLength,
      int pItems) {
     System.out.println("當(dāng)前文件大小:" + pContentLength + "\t已經(jīng)處理:"
       + 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();
     }
    }
    // 處理完后重定向到文件列表頁(yè)面
    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) {
    // 處理完后重定向到文件列表頁(yè)面
    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>您所訪問(wèn)的頁(yè)面不存在!<a href='" + href1 + "'>點(diǎn)擊</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 + "'>點(diǎn)擊</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>操作失敗!文件不存在或文件已經(jīng)被刪除!<a href='" + href1
    + "'>點(diǎn)擊</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>序號(hào)</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(\"您確定要?jiǎng)h除嗎?\");'>刪除</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;
 }
}

其實(shí)UploadService類可以直接實(shí)現(xiàn)service方法,而不用實(shí)現(xiàn)doGet、doPost方法。

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

五、效果圖

1.項(xiàng)目結(jié)構(gòu)圖

2.404頁(yè)面

/*會(huì)匹配所有包括空字符,所以圖片中的路徑會(huì)匹配,在UploadService中的if判斷中出現(xiàn)在else中,因?yàn)榇藭r(shí)的action是空字符。

3.文件列表頁(yè)面

4.上傳表單頁(yè)面

5.下載

6.刪除

7.文件找不到,如果你點(diǎn)刪除時(shí),文件在服務(wù)器上已經(jīng)不存在,那么會(huì)進(jìn)入此頁(yè)面

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

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

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

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • Maven項(xiàng)目分析剔除無(wú)用jar引用的方法步驟

    Maven項(xiàng)目分析剔除無(wú)用jar引用的方法步驟

    這篇文章主要介紹了Maven項(xiàng)目分析剔除無(wú)用jar引用的方法步驟,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-10-10
  • Flink狀態(tài)和容錯(cuò)源碼解析

    Flink狀態(tài)和容錯(cuò)源碼解析

    這篇文章主要為大家介紹了Flink狀態(tài)和容錯(cuò)源碼示例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-12-12
  • SpringCloud OpenFeign基本介紹與實(shí)現(xiàn)示例

    SpringCloud OpenFeign基本介紹與實(shí)現(xiàn)示例

    OpenFeign源于Netflix的Feign,是http通信的客戶端。屏蔽了網(wǎng)絡(luò)通信的細(xì)節(jié),直接面向接口的方式開發(fā),讓開發(fā)者感知不到網(wǎng)絡(luò)通信細(xì)節(jié)。所有遠(yuǎn)程調(diào)用,都像調(diào)用本地方法一樣完成
    2023-02-02
  • 利用Sharding-Jdbc進(jìn)行分庫(kù)分表的操作代碼

    利用Sharding-Jdbc進(jìn)行分庫(kù)分表的操作代碼

    sharding-jdbc是一個(gè)分布式的關(guān)系型數(shù)據(jù)庫(kù)中間件,今天通過(guò)本文給大家介紹利用Sharding-Jdbc進(jìn)行分庫(kù)分表的操作代碼,代碼簡(jiǎn)單易懂對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧
    2022-01-01
  • Springboot指定掃描路徑的實(shí)現(xiàn)示例

    Springboot指定掃描路徑的實(shí)現(xiàn)示例

    本文主要介紹了Springboot指定掃描路徑的實(shí)現(xiàn)示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2024-05-05
  • java占位符替換五種方式小結(jié)

    java占位符替換五種方式小結(jié)

    我們經(jīng)常會(huì)遇到需要替換字符串中的占位符的情況,本文主要介紹了java占位符替換五種方式小結(jié),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2024-06-06
  • 使用Java后端操作Docker的詳細(xì)教程

    使用Java后端操作Docker的詳細(xì)教程

    Docker 是現(xiàn)代開發(fā)和部署流程中不可或缺的一部分,它簡(jiǎn)化了應(yīng)用程序的環(huán)境配置、打包和分發(fā),使得在不同機(jī)器上運(yùn)行相同的應(yīng)用變得更加輕松和一致,本文將詳細(xì)介紹如何使用命令行工具(CMD)操控 Docker 來(lái)配置環(huán)境,需要的朋友可以參考下
    2025-02-02
  • Spring 實(shí)現(xiàn)給Bean屬性注入null值

    Spring 實(shí)現(xiàn)給Bean屬性注入null值

    這篇文章主要介紹了Spring 實(shí)現(xiàn)給Bean屬性注入null值的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-08-08
  • java8中新的Date和Time詳解

    java8中新的Date和Time詳解

    這篇文章主要是java8中新的Date和Time,探討新Date類和Time類背后的設(shè)計(jì)原則,有所需要的小伙伴希望能幫助到你
    2016-07-07
  • Java 輕松入門了解File類的使用

    Java 輕松入門了解File類的使用

    Java文件類以抽象的方式代表文件名和目錄路徑名。該類主要用于文件和目錄的創(chuàng)建、文件的查找和文件的刪除等。File對(duì)象代表磁盤中實(shí)際存在的文件和目錄。通過(guò)以下構(gòu)造方法創(chuàng)建一個(gè)File對(duì)象
    2022-03-03

最新評(píng)論

庆城县| 龙游县| 小金县| 永丰县| 淮阳县| 江阴市| 华蓥市| 广东省| 望奎县| 佛教| 天等县| 开鲁县| 绿春县| 靖宇县| 鹰潭市| 康乐县| 侯马市| 永春县| 当阳市| 梁平县| 梓潼县| 阳山县| 河源市| 沙河市| 正镶白旗| 资阳市| 时尚| 曲周县| 东乡族自治县| 邵阳县| 凤阳县| 通辽市| 西乡县| 呼图壁县| 新干县| 宁武县| 安康市| 邹城市| 齐齐哈尔市| 延寿县| 长顺县|