欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

用fileupload组件实现的大文件上传简单实例

程序员文章站 2023-11-17 21:41:52
1.fileuploadservlet.java文件,实现上传处理 import java.io.file; import java.io.ioexceptio...

1.fileuploadservlet.java文件,实现上传处理

import java.io.file;
import java.io.ioexception;
import java.io.printwriter;
import java.text.decimalformat;
import java.util.iterator;
import java.util.list;

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.fileuploadbase.sizelimitexceededexception;
import org.apache.commons.fileupload.disk.diskfileitemfactory;
import org.apache.commons.fileupload.servlet.servletfileupload;

public class fileuploadservlet extends httpservlet
{
 private static final long serialversionuid = 1l;

 public fileuploadservlet()
 {
 super();
 }

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

 protected void dopost(httpservletrequest request,
 httpservletresponse response) throws servletexception, ioexception
 {

 final long max_size = 2048 * 1024 * 1024;// 设置上传文件最大值为2g,可以改为更大
 // 允许上传的文件格式的列表
 final string[] allowedext = new string[]
 { "exe","jpg","dt" };
 response.setcontenttype("text/html");
 // 设置字符编码为utf-8, 统一编码,处理出现乱码问题
 response.setcharacterencoding("utf-8");

 // 实例化一个硬盘文件工厂,用来配置上传组件servletfileupload
 diskfileitemfactory dfif = new diskfileitemfactory();

 // 用以上工厂实例化上传组件
 servletfileupload sfu = new servletfileupload(dfif);
 // 设置最大上传大小
 sfu.setsizemax(max_size);

 printwriter out = response.getwriter();
 // 从request得到所有上传域的列表
 list filelist = null;
 try
 {
 filelist = sfu.parserequest(request);
 } catch (fileuploadexception e)
 {// 处理文件尺寸过大异常
 if (e instanceof sizelimitexceededexception)
 {
 out.println("文件尺寸超过规定大小:" + max_size + "字节<p />");
 out.println("<a href=\"fileupload.html\" target=\"_top\">返回</a>");
 return;
 }
 e.printstacktrace();
 }
 // 没有文件上传
 if (filelist == null || filelist.size() == 0)
 {
 out.println("请选择上传文件<p />");
 out.println("<a href=\"fileupload.html\" target=\"_top\">返回</a>");
 return;
 }
 //文件大小取两位小数
 decimalformat digit=new decimalformat("0.00");
 // 得到所有上传的文件
 iterator fileitr = filelist.iterator();
 // 循环处理所有文件
 while (fileitr.hasnext())
 {
 fileitem fileitem = null;
 string path = null;
 double size = 0;
 // 得到当前文件
 fileitem = (fileitem) fileitr.next();
 // 忽略简单form字段而不是上传域的文件域(<input type="text" />等)
 if (fileitem == null || fileitem.isformfield())
 {
 continue;
 }

 // 得到文件的大小,k为单位并保留两位小数
 size = (double)fileitem.getsize()/1024;
 if ("".equals(path) || size == 0)
 {
 out.println("<html><head><title>上传处理界面</title></head>");
 out.println("请选择上传文件<p />");
 out.println("<a href=\"fileupload.html\" target=\"_top\">返回</a>");
 out.println("</html>");
 return;
 }
 // 得到文件的完整路径
 path = fileitem.getname();
  
 // 得到去除路径的文件名
 string t_name = path.substring(path.lastindexof("\\") + 1);
 // 得到文件的扩展名(无扩展名时将得到全名)
 string t_ext = t_name.substring(t_name.lastindexof(".") + 1);
 // 拒绝接受规定文件格式之外的文件类型
 int allowflag = 0;
 int allowedextcount = allowedext.length;
 for (; allowflag < allowedextcount; allowflag++)
 {
 if (allowedext[allowflag].equals(t_ext))
 break;
 }
 if (allowflag == allowedextcount)
 {
 out.println("<html><head><title>上传处理界面</title></head>");
 out.println("请上传以下类型的文件<p />");
 for (allowflag = 0; allowflag < allowedextcount; allowflag++)
 out.println("*." + allowedext[allowflag]
 + "   ");
 out.println("<p /><a href=\"fileupload.html\" target=\"_top\">返回</a>");
 out.println("</html>");
 return;
 }
 try
 {
 // 保存文件到服务器根目录下
 fileitem.write(new file("\\"+t_name));
 system.out.println(t_name);
 out.println("<html><head><title>上传处理界面</title></head>");
 out.println("文件名称为:" + path + "<br>");
 out.println("文件上传成功, 已保存为: " + t_name
 + "<br>"+" 文件大小: " + digit.format(size) + "k <p />");
 out.println("<a href=\"fileupload.html\" target=\"_top\">继续上传</a>");
 out.println("</html>");
 } catch (exception e)
 {
 e.printstacktrace();
 }
 }
 }
}

 2.fileupload.html文件,实现上传页面。

<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>文件上传</title>
</head>
<body>
<form action="fileuploadservlet" method="post"
enctype="multipart/form-data">
<input type="file" size="30"
name="file01" /><br>
<pre> <input name="submit" type="submit" value="上传"> <input name="reset" type="reset" value="重置">
</pre>
</form>
</body>
</html>

3.配置web.xml文件中的的servlet和过滤器,过滤器解决上传文件名为中文时出现乱码。

 

<?xml version="1.0" encoding="utf-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
xsi:schemalocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<display-name>fileuploadservlet</display-name>
<servlet-name>fileuploadservlet</servlet-name>
<servlet-class>fileuploadservlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>fileuploadservlet</servlet-name>
<url-pattern>/fileuploadservlet</url-pattern>
</servlet-mapping>

<filter>
<filter-name>setcharacterencoding </filter-name>
<filter-class>com.xulu.encodingchange</filter-class>
<init-param>
<param-name>ignore </param-name>
<param-value>true </param-value>
</init-param>

<init-param>
<param-name>encoding </param-name>
<param-value>utf-8 </param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>setcharacterencoding </filter-name>
<url-pattern>/* </url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<login-config>
<auth-method>basic</auth-method>
</login-config>
</web-app>

4.过滤器文件encodingchange.java和setcharacterencoding.java分别如下,并且在根目录下的web-inf\classes\com\xulu文件夹中放入他它们编译生成的.class文件

package com.xulu;

import java.io.ioexception;

import javax.servlet.*;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;

public class encodingchange implements filter
{
 protected string encoding = null;
 protected filterconfig filterconfig = null;
 protected boolean ignore = true;

 public void destroy()
 {
 this.encoding = null;
 this.filterconfig = null;
 }

 public void dofilter(servletrequest requests, servletresponse responses,
 filterchain chain) throws ioexception, servletexception
 {
 // todo auto-generated method stub
 httpservletrequest request = (httpservletrequest) requests;
 httpservletresponse response = (httpservletresponse) responses;
 if (ignore || request.getcharacterencoding() == null)
 {
 string encoding = selectencoding(request);
 if (encoding != null)
 {
 request.setcharacterencoding(encoding);
 request.getsession().getattribute("login_student");
 request.getsession().getattribute("login_teacher");
 request.getsession().getattribute("login_admin");
 }
 }
 chain.dofilter(request, response);
 }

 public void init(filterconfig filterconfig) throws servletexception
 {
 // todo auto-generated method stub
 this.filterconfig = filterconfig;
 this.encoding = filterconfig.getinitparameter("encoding");
 string value = filterconfig.getinitparameter("ignore");
 if (value == null)
 {
 this.ignore = true;
 } else if (value.equalsignorecase("true"))
 {
 this.ignore = true;
 } else if (value.equalsignorecase("yes"))
 {
 this.ignore = true;
 } else
 {
 this.ignore = false;
 }
 }

 public string selectencoding(servletrequest request)
 {
 return this.encoding;
 }
}
和
package com.xulu;

import java.io.ioexception;

import javax.servlet.*;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;

public class setcharacterencoding implements filter{
protected string encoding=null;
protected filterconfig filterconfig=null;
protected boolean ignore=true;


public void destroy() {
this.encoding=null;
this.filterconfig=null;
}

public void dofilter(servletrequest requests, servletresponse responses,
filterchain chain) throws ioexception, servletexception {
// todo auto-generated method stub
httpservletrequest request=(httpservletrequest)requests;
httpservletresponse response=(httpservletresponse)responses;
if(ignore||request.getcharacterencoding()==null){
string encoding=selectencoding(request);
if(encoding!=null){
request.setcharacterencoding(encoding);
request.getsession().getattribute("login_student");
request.getsession().getattribute("login_teacher");
request.getsession().getattribute("login_admin");
}
}
chain.dofilter(request, response);
}

public void init(filterconfig filterconfig) throws servletexception {
// todo auto-generated method stub
this.filterconfig = filterconfig;
this.encoding = filterconfig.getinitparameter("encoding");
string value = filterconfig.getinitparameter("ignore");
if (value == null) {
this.ignore = true;
} else if (value.equalsignorecase("true")) {
this.ignore = true;
} else if (value.equalsignorecase("yes")) {
this.ignore = true;
} else {
this.ignore = false;
}
}
public string selectencoding(servletrequest request){
return this.encoding;
}
}

5.在浏览器中就可以实现页面的上传了,访问http://localhost:8080/**/fileupload.html就可以了。其中**为自己命名的web文件夹,如doupload,上面的文件都在该目录里,且doupload文件夹放在tomcat的webapp文件夹下。

补充:在上述所有步骤之前需引入三个.jar文件,分别为commons-fileupload-1.2.1.jar,commons-io-1.4.jar和servlet-api.jar网上可以下载到

以上就是小编为大家带来的用fileupload组件实现的大文件上传简单实例的全部内容了,希望对大家有所帮助,多多支持~