当前位置: 移动技术网 > IT编程>开发语言>Java > Java中使用fileupload组件实现文件上传功能的实例代码

Java中使用fileupload组件实现文件上传功能的实例代码

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

安溪房屋出租,proe4.0,马蜂窝三国杀

使用fileupload组件的原因:

request对象提供了一个getinputstream()方法,通过这个方法可以读取到客户端提交过来的数据,但是由于用户可能会同时上传多个文件,在servlet中编程解析这些上传数据是一件非常麻烦的工作。为方便开发人员处理文件上传数据,apache开源组织提供了一个用来处理表单文件上传的一个开源组件(commons-fileupload),该组件性能优异,并且使用及其简单,可以让开发人员轻松实现web文件上传功能。

使用commons-fileupload组件实现文件上传,需要导入该组件相应的支撑jar包:

commons-fileupload和connons-io(commons-upload组件从1.1版本开始,它的工作需要commons-io包的支持)

fileupload组件工作流程:

这里写图片描述

相应的代码框架为:

package pers.msidolphin.uploadservlet.web;
import java.io.file;
import java.io.fileoutputstream;
import java.io.ioexception;
import java.io.inputstream;
import java.io.unsupportedencodingexception;
import java.security.messagedigest;
import java.security.nosuchalgorithmexception;
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 org.apache.commons.fileupload.fileitem;
import org.apache.commons.fileupload.disk.diskfileitemfactory;
import org.apache.commons.fileupload.servlet.servletfileupload;
/**
 * servlet implementation class uploadservlet
 */
public class uploadservlet extends httpservlet {
 private static final long serialversionuid = 1l;
 /**
  * @see httpservlet#httpservlet()
  */
 public uploadservlet() {
  super();
 }
 /**
  * @see httpservlet#doget(httpservletrequest request, httpservletresponse response)
  */
 protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
  //获取解析工厂
  diskfileitemfactory factory = new diskfileitemfactory();
  //得到解析器
  servletfileupload parser = new servletfileupload(factory);
  //解决文件名乱码问题
  parser.setheaderencoding("utf-8");
  //判断上传表单类型
  if(!servletfileupload.ismultipartcontent(request)) {
   return;
  }
  try {
   //调用解析器解析上传数据
   list<fileitem> fileitems = parser.parserequest(request);
   //获得保存上传文件目录的路径
   string uploadpath = request.getservletcontext().getrealpath("/web-inf/upload");
   //遍历list集合
   for (fileitem fileitem : fileitems) {
    //判断是否为普通表单字段
    if(fileitem.isformfield()) {
     //如果是普通表单字段则打印到控制台
     if(fileitem.getstring() == null || "".equals(fileitem.getstring().trim())) {
      continue;
     }
     system.out.println(fileitem.getfieldname() + " = " + new string(fileitem.getstring().getbytes("iso-8859-1"), "utf-8"));
    }else {
     //获得文件路径
     string filepath = fileitem.getname();
     //如果并未上传文件,继续处理下一个字段
     if(filepath == null || "".equals(filepath.trim())) {
      continue;
     }
     system.out.println("处理文件:" + filepath);
     //截取文件名
     string filename = filepath.substring(filepath.lastindexof("\\") + 1);
     string reallyname = this.createfilename(filename);
     string reallypath = this.mkdir(reallyname, uploadpath);
     //下面都是普通的io操作了
     inputstream in = fileitem.getinputstream();
     fileoutputstream out = new fileoutputstream(reallypath + "\\" + reallyname);
     byte[] buffer = new byte[1024];
     int len = 0;
     while((len = in.read(buffer)) > 0) {
      out.write(buffer, 0, len);
     }
     out.close();
     in.close();
    }
   }
   system.out.println("处理完毕...");
  } catch (exception e) {
   // todo auto-generated catch block
   e.printstacktrace();
  }
 }
 /**
  * @see httpservlet#dopost(httpservletrequest request, httpservletresponse response)
  */
 protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
  doget(request, response);
 }
 //随机产生唯一的文件名
 private string createfilename(string filename) throws nosuchalgorithmexception, unsupportedencodingexception {
  string extension = filename.substring(filename.lastindexof("."));
  messagedigest md = messagedigest.getinstance("md5");
  string currenttime = system.currenttimemillis() + "";
  return uuid.randomuuid() + currenttime + extension;
 }
 //根据哈希值产生目录
 private string mkdir(string filename, string uploadpath) {
  int hascode = filename.hashcode();
  //低四位作为一级目录
  int parentdir = hascode & 0xf;
  //二级目录
  int childdir = hascode & 0xff >> 2;
  file file = new file(uploadpath + "\\" + parentdir + "\\" + childdir);
  if(!file.exists()) {
   file.mkdirs();
  }
  uploadpath = uploadpath + "\\" + parentdir + "\\" + childdir;
  return uploadpath;
 }
}

jsp页面 :

<%@ page language="java" contenttype="text/html; charset=utf-8"
 pageencoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<!doctype html public "-//w3c//dtd html 4.01 transitional//en" "http://www.w3.org/tr/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>insert title here</title>
</head>
<body>
 <fmt:setbundle basename="pers.msidolphin.uploadservlet.lang.locale" var="bundle" scope="page"/>
 <form action="<c:url value="/uploadservlet"/>" method="post" enctype="multipart/form-data">
  <fmt:message key="username" bundle="${bundle}"/><input type="text" name="username"/>
  <br/>
  <br/>
  <fmt:message key="file1" bundle="${bundle}"/><input type="file" name="file1"/>
  <br/>
  <br/>
  <fmt:message key="file2" bundle="${bundle}"/><input type="file" name="file2"/>
  <br/>
  <br/>
  <input type="submit" value="<fmt:message key="submit" bundle="${bundle}"/>"/> 
 </form>
</body>
</html>

核心api: diskfileitemfactory类

//设置内存缓冲区的大小,默认为10k,当上传文件大小大于缓冲区大小,fileupload组件将使用临时文件缓存上传文件
public void setsizethreshold(int sizethreshold);
//指定临时文件目录 默认值为system.getproperty("java.io.tmpdir")
public void setrepository(java.io.file respository); 
//构造方法
public diskfileitemfactory(int sizethreshold, java.io.file respository);

核心api: servletfileupload类

//判断上传表单是否为multipart/form-data类型
boolean ismultipartcontent(httpservletrequest request);
//解析request对象,并把表单中的每一个输入项包装成一个fileitem对象,返回这些对象的list集合
list<fileitem> parserequest(httpservletrequest request);
//设置上传文件总量的最大值 单位:字节
void setsizemax(long sizemax);
//设置单个上传文件的最大值 单位:字节
void setfilesizemax(long filesizemax);
//设置编码格式,用于解决上传文件名的乱码问题
void setheaderencoding(string encoding);
//设置文件上传监听器,作用是实时获取已上传文件的大小
void setprogresslistener(progresslistener plistener);

核心api: fileitem类

//判断表单输入项是否为普通输入项(非文件输入项,如果是普通输入项返回true
boolean isformfield();
//获取输入项名称
string getfieldname();
//获得输入项的值
string getstring();
string getstring(string encoding); //可以设置编码,用于解决数据乱码问题
以下是针对非普通字段的:
//获取完整文件名(不同的浏览器可能会有所不同,有的可能包含路径,有的可能只有文件名)
string getname();
//获取文件输入流
inputstream getinputstream();

文件上传的几个注意点:

1、上传文件的文件名乱码问题:servletfileupload对象提供了setheaderencoding(string encoding)方法可以解决中文乱码问题

2、上传数据的中文乱码问题:

解决方法一:new string(fileitem.getstring().getbytes(“iso-8859-1”), “utf-8”)

解决方法二:fileitem.getstring(“utf-8”)

解决方法三:fileitem.getstring(request.getcharacterencoding())

3、上传文件名的唯一性:uuid、md5解决方法很多…

4、保存上传文件的目录最好不要对外公开

5、限制上传文件的大小: servletfileupload对象提供了setfilesizemax(long filesizemax)和setsizemax(long sizemax)方法用于解决这个问题

6、限制文件上传类型:截取后缀名进行判断(好像不太严格,还要研究一番…)

以上所述是小编给大家介绍的java中使用fileupload组件实现文件上传功能的实例代码,希望对大家有所帮助

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网