三种文件上传组件代码.
commons-fileupload上传组件:
(此组件还需要commons-io.jar)
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//上传文件工厂实例
DiskFileItemFactory fileFactory = new DiskFileItemFactory();
//上传文件存储路径
String path = request.getSession().getServletContext().getRealPath("/") + "upload\\";
//创建文件存放的仓库
fileFactory.setRepository(new File(path));
//设置缓存的大小(20M)
fileFactory.setSizeThreshold(1024*1024*20);
//用上传工厂实例创建上传文件对象
ServletFileUpload fileUpload = new ServletFileUpload(fileFactory);
fileUpload.setSizeMax(1024*1024*30);
//fileUpload.setFileSizeMax(1024*1024*10); //这句应该是设置单个文件大小的意思,但加上这句会失败.
//处理页面穿入的表单项
List items = null;
try {
items = fileUpload.parseRequest(request);
} catch (SizeLimitExceededException e) {
request.setAttribute("errorInfo","上传文件超出30M");
request.getRequestDispatcher("jsp/error.jsp").forward(request, response);
return;
} catch (FileUploadException e) {
e.printStackTrace();
request.setAttribute("errorInfo","上传出错");
request.getRequestDispatcher("jsp/error.jsp").forward(request, response);
return;
}
//遍历所有表单项
for (int i = 0; i < items.size(); i++) {
FileItem item = (FileItem)items.get(i);
if ("".equals(item.getName())){//表示没有文件,这里暂时是通过文件名是否为空来判断是否有上传的文件的
continue;
}
//如果这个表单是个普通表单域
if (item.isFormField()){
String name = item.getFieldName();
String value = item.getString("utf-8");
//将表单名和表单值传给页面
request.setAttribute("name", name);
request.setAttribute("value", value);
}
//如果是文件域
else {
//获取文件域的表单域名
String fieldName = item.getFieldName();
//获取文件名
String fileName = item.getName();
//获取文件类型
String contentType = item.getContentType();
//对于上传文件的存放地址来建立一个输出流
String newName = path +
(fileName.lastIndexOf(".") < 0 ?
fileName.substring(0, fileName.length()) :
System.currentTimeMillis() + fileName.substring(fileName.indexOf("."), fileName.length()));
//判断上传文件是否在缓存之中
//这句可能表示上传的文件是否正在缓存向硬盘写入的过程中,但如果加上这句,会上传失败,不知为何...
// if (item.isInMemory()){
FileOutputStream output = new FileOutputStream(newName);
InputStream input = item.getInputStream();
byte[] buffer = new byte[1024];
int len;
while( (len = input.read(buffer)) > 0 ){
output.write(buffer, 0, len);
}
input.close();
output.flush();
output.close();
// }
request.setAttribute("fieldName",fieldName);
request.setAttribute("fileName",fileName);
request.setAttribute("contentType",contentType);
}
}
request.getRequestDispatcher("jsp/uploadResult.jsp").forward(request, response);
}
COS上传组件:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//上传文件存储路径
String path = request.getSession().getServletContext().getRealPath("/") + "upload\\";
//设置上传文件最大限度
MultipartParser mp = null;
try {
mp = new MultipartParser(request,1024*1024*10*2);
} catch (Exception e) {
request.setAttribute("errorInfo","上传文件失败");
request.getRequestDispatcher("jsp/error.jsp").forward(request, response);
return;
}
//代表一个file
Part part = null;
while((part = mp.readNextPart()) != null){
//获取表单名
String fieldName = part.getName();
//如果是文件域
if (part.isFile()){
//取得上传的该文件
FilePart filePart = (FilePart)part;
String fileName = filePart.getFileName();
if (fileName != null && !"".equals(fileName)){
long size = filePart.writeTo(new File(path));//将文件写入硬盘
request.setAttribute("fieldName",fieldName);
request.setAttribute("fileName",fileName);
request.setAttribute("contentType",filePart.getContentType());
}
//表示没有文件
else {
System.out.println("没有文件");
}
}
}
request.getRequestDispatcher("jsp/uploadResult.jsp").forward(request, response);
}
SmartUpload组件:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//上传文件存储路径
String path = request.getSession().getServletContext().getRealPath("/") + "upload\\";
SmartUpload smtUpload = new SmartUpload();
smtUpload.setForcePhysicalPath(true);
smtUpload.initialize(this.getServletConfig(), request, response);
//设置上传的每个文件的大小(10M) //这个能限制单个文件的大小
smtUpload.setMaxFileSize(1024*1024*10);
//设置上传的所有文件总大小(30M)
smtUpload.setTotalMaxFileSize(1024*1024*10*3);
//设置允许上传文件的格式
smtUpload.setAllowedFilesList("jpg,gif,png,jpeg,bmp,JPG,GIF,PNG,JPEG,BMP,zip,rar,exe");
// try {
// //或者设定禁止上传的文件(通过扩展名限制),禁止上传带有exe,bat,jsp,htm,html,js扩展名的文件和没有扩展名的文件。
// smtUpload.setDeniedFilesList("exe,bat,jsp,htm,html,js,,");
// } catch (Exception e) {
// e.printStackTrace();
// request.setAttribute("errorInfo","禁止上传exe,bat,jsp,htm,html,js类型和空类型的文件");
// request.getRequestDispatcher("jsp/error.jsp").forward(request,response);
// return;
// }
try {
smtUpload.upload(); //文件类型错误,文件大小错误的异常都是在这抛出的.
} catch (Exception e){
e.printStackTrace();
request.setAttribute("errorInfo","文件上传错误,请检查上传的文件类型和大小");
request.getRequestDispatcher("jsp/error.jsp").forward(request,response);
return;
}
String fileName = "",fieldName="",contentType="";
//上传文件
for (int i = 0; i < smtUpload.getFiles().getCount(); i++) {
com.jspsmart.upload.File file = smtUpload.getFiles().getFile(i);
//如果该文件不为空
if (!file.isMissing()) {
fieldName = file.getFieldName();
contentType=file.getContentType();
try {
fileName = file.getFileName();
String suffix = fileName.substring(fileName.lastIndexOf("."),fileName.length());
String newFileName = System.currentTimeMillis() + suffix;//产生新的文件名
System.out.println(path+newFileName);
//保存文件
file.saveAs(path + newFileName);
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("errorInfo","文件上传错误,请检查上传的文件类型");
request.getRequestDispatcher("jsp/error.jsp").forward(request,response);
return;
}
}
}
request.setAttribute("fieldName",fieldName);
request.setAttribute("fileName",fileName);
request.setAttribute("contentType",contentType);
request.getRequestDispatcher("jsp/uploadResult.jsp").forward(request, response);
}
upload.jsp:
<form action="<%=basePath %>/xxx.do" enctype="multipart/form-data" method="post">
上传文件:<br />
<input type="file" name="Upload1" contenteditable="false" />
<br /><br />
<input type="file" name="Upload2" contenteditable="false" />
<br /><br />
<input type="file" name="Upload3" contenteditable="false" />
<br /><br />
<input type="submit" value="上传" />
</form>
四、通过字节流实现文件上传
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
java.io.InputStream is = request.getInputStream();
java.io.FileOutputStream fos = new java.io.FileOutputStream("d:\\out.txt");
byte[] buffer = new byte[8192];
int count = 0;
while((count = is.read(buffer)) >0)
{
fos.write(buffer, 0, count);
}
fos.close();
}
五、使用apache commons-io的FileUtils.copyFile简单地复制文件
用一般的方法,我们要复制一个文件,可能需要读取源文件,生成流对象,再写入一个新的文件中,使用apache commons-io很容就可以处理文件的复制。
下面的例子演示我们怎样使用FileUtils.copyFile方法在同一个文件夹复制文件和使用FileUtils.copyFileToDirectory方法复制到指定的文件夹中。其中System.getProperty("java.io.tmpdir")为通过JVM读取java.io.tmpdir属性取得临时文件夹,每种操作系统有所不同,Windows一般是C:\DOCUME~1\用户~1\LOCALS~1\Temp,Solaris一般是:/var/tmp/,Linux和Mac OS X一般是:/tmp,Windows的java.io.tmpdir属性值可以看环境变量->用户变量中的TMP。
当然我们一般使用的是绝对或相对路径,如要复制到F:\ajava目录中,我们只需将targetDir改成File targetDir = new File("F:\\ajava");运行后就可以看到结果。
package ajava.sample.apache;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
public class AjavaFileCopyExample {
public static void main(String[] args)
{
// 源File对象
File source = new File("ajava.txt");
// 备份的File对象
File target = new File("ajava-backup.txt");
//通过JVM读取java.io.tmpdir属性取得临时文件夹
File targetDir = new File(System.getProperty("java.io.tmpdir"));
try
{
//在同一个文件夹复制文件
System.out.println("复制 " + source + " 文件到 " + target);
FileUtils.copyFile(source, target);
// 根据指定的文件夹复制
System.out.println("复制 " + source + " 文件到" + targetDir + "目录");
FileUtils.copyFileToDirectory(source, targetDir);
} catch (IOException e)
{
// Errors will be reported here if any error occures during copying
// the file
e.printStackTrace();
}
}
}
输出结果为:
复制 ajava.txt 文件到 ajava-backup.txt
复制 ajava.txt 文件到C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp目录
再查看对应的文件夹,就可以发现备份文件。
六、struts2的文件上传
http://bbs.chinaunix.net/thread-1845099-1-1.html