当前位置: 移动技术网 > IT编程>开发语言>Java > java文件上传下载功能实现代码

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

2019年07月22日  | 移动技术网IT编程  | 我要评论

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

前台:

1. 提交方式:post
2. 表单中有文件上传的表单项: <input type=”file” />
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<fileitem> 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(); // 上传文件流

      /*
       * 四、文件名重名
       * 对于不同用户readme.txt文件,不希望覆盖!
       * 后台处理: 给用户添加一个唯一标记!
       */
      // 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 {
  /*
  request.getparameter(""); // get/post
  request.getquerystring(); // 获取get提交的数据 
  request.getinputstream(); // 获取post提交的数据 */

  /***********手动获取文件上传表单数据************/

  //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

<body> 
  <a href="${pagecontext.request.contextpath }/upload.jsp">文件上传</a>    
  <a href="${pagecontext.request.contextpath }/fileservlet?method=downlist">文件下载</a> 

</body>

upload.jsp

<body> 
  <form name="frm_test" action="${pagecontext.request.contextpath }/fileservlet?method=upload" method="post" enctype="multipart/form-data">
   <%--<input type="hidden" name="method" value="upload">--%>

   用户名:<input type="text" name="username"> <br/>
  文件: <input type="file" name="file_img"> <br/>

  <input type="submit" value="提交">
  </form>
 </body>

fileservlet.java

/**
 * 处理文件上传与下载
 * @author jie.yuan
 *
 */
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);
  }
 }


 /**
  * 1. 上传
  */
 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<fileitem> 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();
  }


 }


 /**
  * 2. 进入下载列表
  */
 private void downlist(httpservletrequest request, httpservletresponse response)
 throws servletexception, ioexception {

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

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

  //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<list.length; i++){
    // 全名
    string filename = list[i];
    // 短名
    string shortname = filename.substring(filename.lastindexof("#")+1);
    // 封装
    filenames.put(filename, shortname);
   }
  }

  // 3. 保存到request域
  request.setattribute("filenames", filenames);
  // 4. 转发
  request.getrequestdispatcher("/downlist.jsp").forward(request, response);

 }


 /**
  * 3. 处理下载
  */
 private void down(httpservletrequest request, httpservletresponse response)
 throws servletexception, ioexception {

  // 获取用户下载的文件名称(url地址后追加数据,get)
  string filename = request.getparameter("filename");
  filename = new string(filename.getbytes("iso8859-1"),"utf-8");

  // 先获取上传目录路径
  string basepath = getservletcontext().getrealpath("/upload");
  // 获取一个文件流
  inputstream in = new fileinputstream(new file(basepath,filename));

  // 如果文件名是中文,需要进行url编码
  filename = urlencoder.encode(filename, "utf-8");
  // 设置下载的响应头
  response.setheader("content-disposition", "attachment;filename=" + filename);

  // 获取response字节流
  outputstream out = response.getoutputstream();
  byte[] b = new byte[1024];
  int len = -1;
  while ((len = in.read(b)) != -1){
   out.write(b, 0, len);
  }
  // 关闭
  out.close();
  in.close();


 }

 public void dopost(httpservletrequest request, httpservletresponse response)
   throws servletexception, ioexception {
  this.doget(request, response);
 }

}

以上就是本文的全部内容,希望对大家的学习有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网