JavaServlet的文件上传和下载如何实现方法

喜欢不是最大的动力,害怕才是,父母的衰老,亲人的眼泪,因为害怕很多事才坚持下来,怕到发抖,所以拼命坚持。

先分析一下上传文件的流程

1-先通过前段页面中的选择文件选择要上传的图片

index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"
 contentType="text/html; charset=UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
 <head>
  <title>My JSP 'index.jsp' starting page</title>
  <meta http-equiv="content-type" content="text/html;charset=utf-8">
  <meta http-equiv="pragma" content="no-cache">
  <meta http-equiv="cache-control" content="no-cache">
  <meta http-equiv="expires" content="0">
  <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
  <meta http-equiv="description" content="This is my page">
  
  <script type="text/javascript" src="js/jquery.min.js"></script>
  <script type="text/javascript" src="js/common.js"></script>
  <script type="text/javascript" src="js/ajaxfileupload.js"></script>
 </head>
 <body>
  <input type="file" value="上传" name="inputImage" id="inputImage">
  <input type="button" value="上传" id="upload">
  
  <a id="downLoad">下载</a>
 </body>
</html>

2-点击提交按钮,通过ajax的文件上传访问服务器端

common.js  

var path = (function() {
 //获取当前网址
 var curWwwPath = window.document.location.href;
 //获取主机地址之后的目录
 var pathName = window.document.location.pathname;
 var pos = curWwwPath.indexOf(pathName);
 //获取主机地址
 var localhostPath = curWwwPath.substring(0, pos);
 //获取带"/"的项目名
 var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1);
 return {
   curWwwPath: curWwwPath,
   pathName: pathName,
   localhostPath: localhostPath,
   projectName: projectName,
   //部署路径
   deployPath: localhostPath + projectName
  };
})();
// 文件下载
$("a[id=downLoad]").click(function(){
 window.location.rel="nofollow noopener noreferrer" href=path.deployPath+"/fileDown";
});
// 文件上传
$("input[id=upload]").click(function() {
 $.ajaxFileUpload( {
  url : path.deployPath + "/fileUp", // 处理页面的绝对路径
  fileElementId : "inputImage", //file空间的id属性
  dataType : "json",
  success : function(data) {
   alert("上传成功");
  }
 });
});

3-服务器端响应保存或者下载

保存上传文件的FileUpload.java

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import com.stu.util.HttpUtil;
/**
 * 文件名称: com.stu.fileupload.FileUpload.java<br/>
 * 初始作者: Administrator<br/>
 * 创建日期: 2018-1-31<br/>
 * 功能说明: 文件上传 <br/>
 * =================================================<br/>
 * 修改记录:<br/>
 * 修改作者 日期 修改内容<br/>
 * ================================================<br/>
 * Copyright (c) 2010-2011 .All rights reserved.<br/>
 */
public class FileUpload extends HttpServlet {
 private static final long serialVersionUID = 1L;
 @Override
 protected void service(HttpServletRequest req, HttpServletResponse res)
 throws ServletException, IOException {
  // 获取到当前服务器所在的路径
  String serverPath = req.getSession().getServletContext().getRealPath("/");
  // 设置保存上传文件的路径
  String saveDirPath = serverPath + "img";
  File saveDirPathFileObj = new File(saveDirPath);
  // 如果当用来存放文件的目录不存在时,要创建该目录
  if (!saveDirPathFileObj.exists()) {
   saveDirPathFileObj.mkdirs();
  }
  // 创建一个解析器工厂
  DiskFileItemFactory factory = new DiskFileItemFactory();
  // 设置工厂的缓存区大小
  factory.setSizeThreshold(5 * 1024);
  // 文件上传的解析器(文件上传对象)
  ServletFileUpload upload = new ServletFileUpload(factory);
  // 设置上传文件的最大值
  upload.setSizeMax(3 * 1024 * 1024);
  // 设置编码格式
  upload.setHeaderEncoding("UTF-8");
  try {
   // 上传以后的文件名
   List<String> uploadFileNames = new ArrayList<String>();
   List<FileItem> fileItems = upload.parseRequest(req);
   System.out.println(fileItems);
   for (FileItem file : fileItems) {
    // 新的文件名
    String saveFileName = UUID.randomUUID().toString().replace("-", "");
    // 文件的后缀
    String oldFileName = new String(file.getName().getBytes(),
    "UTF-8");
    System.out.println("oldFileName" + oldFileName);
    String fileType = oldFileName.substring(oldFileName.lastIndexOf("."));
    // 新的文件路径
    String saveFilePath = saveDirPath + File.separator
    + saveFileName + fileType;
    uploadFileNames.add(saveFileName + fileType);
    // 保存上传的文件
    file.write(new File(saveFilePath));
   }
   System.out.println(uploadFileNames);
   HttpUtil.setAttribute(req, "urls", uploadFileNames);
   res.setContentType("application/json;charset=utf-8");
   PrintWriter pw = res.getWriter();
   pw.print(JSONArray.fromObject(uploadFileNames));
  } catch (FileUploadException e) {
   e.printStackTrace();
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
}

下载文件的FileDownload.java

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import com.stu.util.HttpUtil;
/**
 * 文件名称: com.stu.fileupload.FileUpload.java<br/>
 * 初始作者: Administrator<br/>
 * 创建日期: 2018-1-31<br/>
 * 功能说明: 文件上传 <br/>
 * =================================================<br/>
 * 修改记录:<br/>
 * 修改作者 日期 修改内容<br/>
 * ================================================<br/>
 * Copyright (c) 2010-2011 .All rights reserved.<br/>
 */
public class FileUpload extends HttpServlet {
 private static final long serialVersionUID = 1L;
 @Override
 protected void service(HttpServletRequest req, HttpServletResponse res)
 throws ServletException, IOException {
  // 获取到当前服务器所在的路径
  String serverPath = req.getSession().getServletContext().getRealPath("/");
  // 设置保存上传文件的路径
  String saveDirPath = serverPath + "img";
  File saveDirPathFileObj = new File(saveDirPath);
  // 如果当用来存放文件的目录不存在时,要创建该目录
  if (!saveDirPathFileObj.exists()) {
   saveDirPathFileObj.mkdirs();
  }
  // 创建一个解析器工厂
  DiskFileItemFactory factory = new DiskFileItemFactory();
  // 设置工厂的缓存区大小
  factory.setSizeThreshold(5 * 1024);
  // 文件上传的解析器(文件上传对象)
  ServletFileUpload upload = new ServletFileUpload(factory);
  // 设置上传文件的最大值
  upload.setSizeMax(3 * 1024 * 1024);
  // 设置编码格式
  upload.setHeaderEncoding("UTF-8");
  try {
   // 上传以后的文件名
   List<String> uploadFileNames = new ArrayList<String>();
   List<FileItem> fileItems = upload.parseRequest(req);
   System.out.println(fileItems);
   for (FileItem file : fileItems) {
    // 新的文件名
    String saveFileName = UUID.randomUUID().toString().replace("-", "");
    // 文件的后缀
    String oldFileName = new String(file.getName().getBytes(),
    "UTF-8");
    System.out.println("oldFileName" + oldFileName);
    String fileType = oldFileName.substring(oldFileName.lastIndexOf("."));
    // 新的文件路径
    String saveFilePath = saveDirPath + File.separator
    + saveFileName + fileType;
    uploadFileNames.add(saveFileName + fileType);
    // 保存上传的文件
    file.write(new File(saveFilePath));
   }
   System.out.println(uploadFileNames);
   HttpUtil.setAttribute(req, "urls", uploadFileNames);
   res.setContentType("application/json;charset=utf-8");
   PrintWriter pw = res.getWriter();
   pw.print(JSONArray.fromObject(uploadFileNames));
  } catch (FileUploadException e) {
   e.printStackTrace();
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
}

这里面用到了一个HttpUtil类,代码如下:

import javax.servlet.FilterConfig;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
/**
 * 文件名称_com.niit.model2.util.Httputil.java</br>
 * 初始作逯ܿAdministrator</br>
 * 创建日期_2018-1-23</br>
 * 功能说明_这里用一句话描述这个类的作用--此句话需删除 <br/>
 * =================================================<br/>
 * 修改记录_br/>
 * 修改作迠日期 修改内容<br/>
 * ================================================<br/>
 * Copyright (c) 2010-2011 .All rights reserved.<br/>
 */
public class HttpUtil {
  private HttpUtil() {
  }
  /**
   * 方法描述: [用于向不同的作用域存放属性]</br>
   * 初始作迺 Administrator<br/>
   * 创建日期: 2018-1-23-上午11:24:45<br/>
   * 弿Nj版本: 2.0.0<br/>
   * =================================================<br/>
   * 修改记录_br/>
   * 修改作迠日期 修改内容<br/>
   * ================================================<br/>
   * void
   */
  public static void setAttribute(Object scopeObj, String name, Object value) {
    if (scopeObj instanceof HttpServletRequest) {
      ((HttpServletRequest) scopeObj).setAttribute(name, value);
    }
    if (scopeObj instanceof HttpSession) {
      ((HttpSession) scopeObj).setAttribute(name, value);
    }
    if (scopeObj instanceof ServletContext) {
      ((ServletContext) scopeObj).setAttribute(name, value);
    }
  }
  /**
   * 方法描述: [获取作用域中指定名称的属性思</br>
   * 初始作迺 Administrator<br/>
   * 创建日期: 2018-1-23-上午11:29:17<br/>
   * 弿Nj版本: 2.0.0<br/>
   * =================================================<br/>
   * 修改记录_br/>
   * 修改作迠日期 修改内容<br/>
   * ================================================<br/>
   * 
   * @param scopeObj
   * @param name
   * @return
   *     Object
   */
  public static Object getAttribute(Object scopeObj, String name) {
    if (scopeObj instanceof HttpServletRequest) {
      return ((HttpServletRequest) scopeObj).getAttribute(name);
    }
    if (scopeObj instanceof HttpSession) {
      return ((HttpSession) scopeObj).getAttribute(name);
    }
    if (scopeObj instanceof ServletContext) {
      return ((ServletContext) scopeObj).getAttribute(name);
    }
    return null;
  }
  /**
   * 方法描述: [获取上下文对象的方法]</br>
   * 初始作迺 Administrator<br/>
   * 创建日期: 2018-1-23-上午11:31:26<br/>
   * 弿Nj版本: 2.0.0<br/>
   * =================================================<br/>
   * 修改记录_br/>
   * 修改作迠日期 修改内容<br/>
   * ================================================<br/>
   * 
   * @return
   *     ServletContext
   */
  public static ServletContext getServletContext(Object sourceObj) {
    if (sourceObj instanceof HttpServletRequest) {
      return ((HttpServletRequest) sourceObj).getSession().getServletContext();
    }
    if (sourceObj instanceof ServletConfig) {
      return ((ServletConfig) sourceObj).getServletContext();
    }
    if (sourceObj instanceof FilterConfig) {
      return ((FilterConfig) sourceObj).getServletContext();
    }
    return null;
  }
  /**
   * 方法描述: [获取项目的实际路径]</br>
   * 初始作迺 Administrator<br/>
   * 创建日期: 2018-1-23-上午11:45:47<br/>
   * 弿Nj版本: 2.0.0<br/>
   * =================================================<br/>
   * 修改记录_br/>
   * 修改作迠日期 修改内容<br/>
   * ================================================<br/>
   * 
   * @param req
   * @return
   *     String
   */
  public static String getContextPath(HttpServletRequest req) {
    return req.getContextPath();
  }
}

当然,代码编辑好了也不要忘了在 WebRoot/WEB-INF/web.xml 中添加新建的Servlet,就是刚刚的两个Java文件啦

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
  http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <!-- 文件上传 -->
  <servlet>
    <servlet-name>fileUpload</servlet-name>
    <servlet-class>com.stu.fileupload.FileUpload</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>fileUpload</servlet-name>
    <url-pattern>/fileUp</url-pattern>
  </servlet-mapping>
  <!-- 文件下载 -->
  <servlet>
    <servlet-name>fileDownload</servlet-name>
    <servlet-class>com.stu.fileupload.FileDownload</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>fileDownload</servlet-name>
    <url-pattern>/fileDown</url-pattern>
  </servlet-mapping>
</web-app>

这样的话就可以运行啦。

TIP: 不要忘记相关的jar包和 js 包哦

在 WebRoot / WEB-INF / lib 下,有 commons-fileupload.jar 和 commons-io.jar ,另外 json-lib-x.x.x-jdkxx.jar 包是用来把上传的返回数据修改为JSON格式的

在 WebRoot / js 下,导入 jquery.js , common.js , ajaxfileupload.js

以上这篇JavaServlet的文件上传和下载实现方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

标签: JavaServlet