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

Apache Commons fileUpload实现文件上传之一

程序员文章站 2024-03-09 16:04:41
废话不多说了,直奔主题了。 需要两个jar包: commons-fileupload.jar commons io的jar包(本文使用commons-io-2...

废话不多说了,直奔主题了。

需要两个jar包:

commons-fileupload.jar

commons io的jar包(本文使用commons-io-2.4.jar)

利用servlet来实现文件上传。

package web.servlet;

import java.io.ioexception;
import javax.servlet.servletexception;
import javax.servlet.annotation.webservlet;
import javax.servlet.http.httpservlet;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
import java.io.file;
import java.util.iterator;
import java.util.list;
import org.apache.commons.fileupload.fileitem;
import org.apache.commons.fileupload.disk.diskfileitemfactory;
import org.apache.commons.fileupload.servlet.servletfileupload;
/**
* servlet implementation class uploadservlet
*/
@webservlet("/uploadservlet")
public class uploadservlet extends httpservlet {
private static final long serialversionuid = 1l;
private string uploadpath = "d:\\temp"; // 上传文件的目录
private string temppath = "d:\\temp\\buffer\\"; // 临时文件目录
file temppathfile;
public void dopost(httpservletrequest request, httpservletresponse response)
throws ioexception, servletexception {
try {
// create a factory for disk-based file items
diskfileitemfactory factory = new diskfileitemfactory();
// set factory constraints
factory.setsizethreshold(4096); // 设置缓冲区大小,这里是4kb
factory.setrepository(temppathfile);// 设置缓冲区目录
// create a new file upload handler
servletfileupload upload = new servletfileupload(factory);
// set overall request size constraint
upload.setsizemax(4194304); // 设置最大文件尺寸,这里是4mb
list<fileitem> items = upload.parserequest(request);// 得到所有的文件
iterator<fileitem> i = items.iterator();
while (i.hasnext()) {
fileitem fi = (fileitem) i.next();
string filename = fi.getname();
if (filename != null) {
file fullfile = new file(fi.getname());
file savedfile = new file(uploadpath, fullfile.getname());
fi.write(savedfile);
}
}
system.out.print("upload succeed");
} catch (exception e) {
// 可以跳转出错页面
e.printstacktrace();
}
}
public void init() throws servletexception {
file uploadfile = new file(uploadpath);
if (!uploadfile.exists()) {
uploadfile.mkdirs();
}
file temppathfile = new file(temppath);
if (!temppathfile.exists()) {
temppathfile.mkdirs();
}
}
}

jsp

<%@ page language="java" contenttype="text/html; charset=iso--"
pageencoding="utf-"%>
<!doctype html public "-//wc//dtd html . transitional//en" "http://www.w.org/tr/html/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=gb">
<title>file upload</title>
</head>
<body>
<!-- // action="fileupload"对应web.xml中<servlet-mapping>中<url-pattern>的设置. -->
<form name="myform" action="uploadservlet" method="post"
enctype="multipart/form-data">
file:<br>
<input type="file" name="myfile"><br>
<br>
<input type="submit" name="submit" value="commit">
</form>
</body>
</html> 

这样就能简单实现一个文件上传功能了,当然这是最最最基本的,继续研究中。