栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java文件上传下载功能实现代码

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java文件上传下载功能实现代码

本文实例为大家分享了文件上传下载java实现代码,供大家参考,具体内容如下

前台:

1. 提交方式:post
2. 表单中有文件上传的表单项:
3. 指定表单类型:
    默认类型:enctype="application/x-www-form-urlencoded"
    文件上传类型:multipart/form-data

FileUpload

文件上传功能开发中比较常用,apache也提供了文件上传组件!
FileUpload组件:
1. 下载源码
2. 项目中引入jar文件
commons-fileupload-1.2.1.jar 【文件上传组件核心jar包】
commons-io-1.4.jar 【封装了对文件处理的相关工具类】

使用:

public class UploadServlet extends HttpServlet {

 // upload目录,保存上传的资源
 public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {

  


  try {
   // 1. 文件上传工厂
   FileItemFactory factory = new DiskFileItemFactory();
   // 2. 创建文件上传核心工具类
   ServletFileUpload upload = new ServletFileUpload(factory);

   // 一、设置单个文件允许的最大的大小: 30M
   upload.setFileSizeMax(30*1024*1024);
   // 二、设置文件上传表单允许的总大小: 80M
   upload.setSizeMax(80*1024*1024);
   // 三、 设置上传表单文件名的编码
   // 相当于:request.setCharacterEncoding("UTF-8");
   upload.setHeaderEncoding("UTF-8");


   // 3. 判断: 当前表单是否为文件上传表单
   if (upload.isMultipartContent(request)){
    // 4. 把请求数据转换为一个个FileItem对象,再用集合封装
    List list = upload.parseRequest(request);
    // 遍历: 得到每一个上传的数据
    for (FileItem item: list){
     // 判断:普通文本数据
     if (item.isFormField()){
      // 普通文本数据
      String fieldName = item.getFieldName(); // 表单元素名称
      String content = item.getString();  // 表单元素名称, 对应的数据
      //item.getString("UTF-8"); 指定编码
      System.out.println(fieldName + " " + content);
     }
     // 上传文件(文件流) ----> 上传到upload目录下
     else {
      // 普通文本数据
      String fieldName = item.getFieldName(); // 表单元素名称
      String name = item.getName();   // 文件名    
      String content = item.getString();  // 表单元素名称, 对应的数据
      String type = item.getContentType(); // 文件类型
      InputStream in = item.getInputStream(); // 上传文件流

      
      // a. 随机生成一个唯一标记
      String id = UUID.randomUUID().toString();
      // b. 与文件名拼接
      name = id +"#"+ name;

      // 获取上传基路径
      String path = getServletContext().getRealPath("/upload");
      // 创建目标文件
      File file = new File(path,name);

      // 工具类,文件上传
      item.write(file);
      item.delete(); //删除系统产生的临时文件

      System.out.println();
     }

    }

   }
   else {
    System.out.println("当前表单不是文件上传表单,处理失败!");
   }
  } catch (Exception e) {
   e.printStackTrace();
  }


 }


 // 手动实现过程
 private void upload(HttpServletRequest request) throws IOException,
   UnsupportedEncodingException {
  

  

  //1. 获取表单数据流
  InputStream in = request.getInputStream();
  //2. 转换流
  InputStreamReader inStream = new InputStreamReader(in, "UTF-8");
  //3. 缓冲流
  BufferedReader reader = new BufferedReader(inStream);
  // 输出数据
  String str = null;
  while ((str = reader.readLine()) != null) {
   System.out.println(str);
  }

  // 关闭
  reader.close();
  inStream.close();
  in.close();
 }

 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  this.doGet(request, response);
 }

}

案例:

Index.jsp

 
  文件上传    
  文件下载 



Upload.jsp

 
  
 

FileServlet.java


public class FileServlet extends HttpServlet {

 public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {

  // 获取请求参数: 区分不同的操作类型
  String method = request.getParameter("method");
  if ("upload".equals(method)) {
   // 上传
   upload(request,response);
  }

  else if ("downList".equals(method)) {
   // 进入下载列表
   downList(request,response);
  }

  else if ("down".equals(method)) {
   // 下载
   down(request,response);
  }
 }


 
 private void upload(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException {

  try {
   // 1. 创建工厂对象
   FileItemFactory factory = new DiskFileItemFactory();
   // 2. 文件上传核心工具类
   ServletFileUpload upload = new ServletFileUpload(factory);
   // 设置大小限制参数
   upload.setFileSizeMax(10*1024*1024); // 单个文件大小限制
   upload.setSizeMax(50*1024*1024);  // 总文件大小限制
   upload.setHeaderEncoding("UTF-8");  // 对中文文件编码处理

   // 判断
   if (upload.isMultipartContent(request)) {
    // 3. 把请求数据转换为list集合
    List list = upload.parseRequest(request);
    // 遍历
    for (FileItem item : list){
     // 判断:普通文本数据
     if (item.isFormField()){
      // 获取名称
      String name = item.getFieldName();
      // 获取值
      String value = item.getString();
      System.out.println(value);
     } 
     // 文件表单项
     else {
      
      // a. 获取文件名称
      String name = item.getName();
      // ----处理上传文件名重名问题----
      // a1. 先得到唯一标记
      String id = UUID.randomUUID().toString();
      // a2. 拼接文件名
      name = id + "#" + name;      

      // b. 得到上传目录
      String basePath = getServletContext().getRealPath("/upload");
      // c. 创建要上传的文件对象
      File file = new File(basePath,name);
      // d. 上传
      item.write(file);
      item.delete(); // 删除组件运行时产生的临时文件
     }
    }
   }
  } catch (Exception e) {
   e.printStackTrace();
  }


 }


 
 private void downList(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException {

  // 实现思路:先获取upload目录下所有文件的文件名,再保存;跳转到down.jsp列表展示

  //1. 初始化map集合Map<包含唯一标记的文件名, 简短文件名> ;
  Map fileNames = new HashMap();

  //2. 获取上传目录,及其下所有的文件的文件名
  String bathPath = getServletContext().getRealPath("/upload");
  // 目录
  File file = new File(bathPath);
  // 目录下,所有文件名
  String list[] = file.list();
  // 遍历,封装
  if (list != null && list.length > 0){
   for (int i=0; i
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/149901.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号