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

JAVA使用commos-fileupload实现文件上传与下载实例解析

程序员文章站 2024-03-08 14:45:05
首先给大家介绍一文件的上传 实体类 import java.sql.timestamp; /** * * @decription 文件上传实体...

首先给大家介绍一文件的上传

实体类

import java.sql.timestamp; 
/** 
* 
* @decription 文件上传实体类 
* 
*/ 
public class upfile { 
private string id;// id主键 使用uuid随机生成 
private string uuidname; // uuid名称 
private string filename;//文件名称 
private string savepath; // 保存路径 
private timestamp uploadtime; // 上传时间 
private string description;// 文件描述 
private string username; // 用户名 
public upfile() { 
super(); 
} 
public upfile(string id, string uuidname, string filename, string savepath, 
timestamp uploadtime, string description, string username) { 
super(); 
this.id = id; 
this.uuidname = uuidname; 
this.filename = filename; 
this.savepath = savepath; 
this.uploadtime = uploadtime; 
this.description = description; 
this.username = username; 
} 
public string getdescription() { 
return description; 
} 
public string getfilename() { 
return filename; 
} 
public string getid() { 
return id; 
} 
public string getsavepath() { 
return savepath; 
} 
public timestamp getuploadtime() { 
return uploadtime; 
} 
public string getusername() { 
return username; 
} 
public string getuuidname() { 
return uuidname; 
} 
public void setdescription(string description) { 
this.description = description; 
} 
public void setfilename(string filename) { 
this.filename = filename; 
} 
public void setid(string id) { 
this.id = id; 
} 
public void setsavepath(string savepath) { 
this.savepath = savepath; 
} 
public void setuploadtime(timestamp uploadtime) { 
this.uploadtime = uploadtime; 
} 
public void setusername(string username) { 
this.username = username; 
} 
public void setuuidname(string uuidname) { 
this.uuidname = uuidname; 
} 
} 

页面

<%@ page language="java" import="java.util.*" pageencoding="utf-8"%> 
<% 
string path = request.getcontextpath(); 
string basepath = request.getscheme()+"://"+request.getservername()+":"+request.getserverport()+path+"/"; 
%> 
<!doctype html public "-//w3c//dtd html 4.01 transitional//en"> 
<html> 
<head> 
<base href="<%=basepath%>"> 
<title>my jsp 'upload.jsp' starting page</title> 
<meta http-equiv="pragma" content="no-cache"> 
<meta http-equiv="cache-control" content="no-cache"> 
<meta http-equiv="expires" content="0"> 
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 
<meta http-equiv="description" content="this is my page"> 
<!-- 
<link rel="stylesheet" type="text/css" href="styles.css"> 
--> 
</head> 
<body> 
<h1>文件上传</h1> 
<form action="${pagecontext.request.contextpath }/upload" method="post" enctype="multipart/form-data"> 
<table> 
<tr> 
<td> 上传用户名:</td> 
<td><input type="text" name="username"/></td> 
</tr> 
<tr> 
<td> 上传文件:</td> 
<td><input type="file" name="file"/></td> 
</tr> 
<tr> 
<td> 描述:</td> 
<td><textarea rows="5" cols="50" name="description"></textarea></td> 
</tr> 
<tr> 
<td><input type="submit" value="上传开始"/></td> 
</tr> 
</table> 
</form> 
<div>${msg }</div> 
<a href="${pagecontext.request.contextpath }/index.jsp">返回主页</a> 
</body> 
</html> 

servlet

import java.io.ioexception; 
import javax.servlet.servletexception; 
import javax.servlet.http.httpservlet; 
import javax.servlet.http.httpservletrequest; 
import javax.servlet.http.httpservletresponse; 
import org.apache.commons.fileupload.fileuploadbase.filesizelimitexceededexception; 
import org.apache.commons.fileupload.fileuploadbase.sizelimitexceededexception; 
import org.apache.commons.fileupload.servlet.servletfileupload; 
import com.itheima.domain.upfile; 
import com.itheima.exception.myexception; 
import com.itheima.service.upfileservice; 
import com.itheima.service.impl.upfileserviceimpl; 
import com.itheima.untils.webuntil; 
public class uploadfileservlet extends httpservlet { 
public void doget(httpservletrequest request, httpservletresponse response) 
throws servletexception, ioexception { 
dopost(request, response); 
} 
public void dopost(httpservletrequest request, httpservletresponse response) 
throws servletexception, ioexception { 
//判断表单是不是多个部分组成的 
if(!servletfileupload.ismultipartcontent(request)){ 
request.setattribute("msg", "表单个设置错误,请检查enctype属性是是否设置正确"); 
request.getrequestdispatcher("/upload.jsp").forward(request, response); 
return ; 
} 
//是多部分组成的就获取并遍历返回一个文件上传对象,包含上传的所有信息 
try { 
upfile upfile=webuntil.upload(request); 
upfileservice upfileservice=new upfileserviceimpl(); 
boolean flag=upfileservice.add(upfile); 
if(flag){ 
request.setattribute("msg", "上传成功"); 
request.getrequestdispatcher("/upload.jsp").forward(request, response); 
return ; 
}else{ 
request.setattribute("msg", "上传失败,请重试"); 
request.getrequestdispatcher("/upload.jsp").forward(request, response); 
return ; 
} 
}catch (filesizelimitexceededexception e) { 
e.printstacktrace(); 
request.setattribute("msg", "单个文件大小 ,超过最大限制"); 
request.getrequestdispatcher("/upload.jsp").forward(request, response); 
return ; 
} catch (sizelimitexceededexception e) { 
e.printstacktrace(); 
request.setattribute("msg", "总文件大小 ,超过最大限制"); 
request.getrequestdispatcher("/upload.jsp").forward(request, response); 
return ; 
} 
} 
}

工具类

import java.io.file; 
import java.io.filenotfoundexception; 
import java.io.fileoutputstream; 
import java.io.ioexception; 
import java.io.inputstream; 
import java.io.outputstream; 
import java.io.unsupportedencodingexception; 
import java.util.arraylist; 
import java.util.list; 
import java.util.uuid; 
import javax.servlet.http.httpservletrequest; 
import org.apache.commons.fileupload.fileitem; 
import org.apache.commons.fileupload.fileuploadbase; 
import org.apache.commons.fileupload.fileuploadbase.filesizelimitexceededexception; 
import org.apache.commons.fileupload.fileuploadbase.sizelimitexceededexception; 
import org.apache.commons.fileupload.fileuploadexception; 
import org.apache.commons.fileupload.progresslistener; 
import org.apache.commons.fileupload.disk.diskfileitemfactory; 
import org.apache.commons.fileupload.servlet.servletfileupload; 
import com.itheima.domain.upfile; 
import com.itheima.exception.myexception; 
/** 
* 文件上传工具类 
* @decription todo 
* 
*/ 
public class webuntil { 
/** 
* 文件上传的方法 
* @param request 请求参数传入 
* @return 返回一个upfile对象 
* @throws filesizelimitexceededexception 
* @throws sizelimitexceededexception 
* @throws ioexception 
*/ 
public static upfile upload(httpservletrequest request) throws filesizelimitexceededexception, sizelimitexceededexception { 
upfile upfile=new upfile(); 
arraylist<string> filelist=initlist(); 
try { 
//获取磁盘文件对象工厂 
diskfileitemfactory factory=new diskfileitemfactory(); 
string tmp=request.getsession().getservletcontext().getrealpath("/tmp"); 
system.out.println(tmp); 
//初始化工厂 
setfactory(factory,tmp); 
//获取文件上传解析器 
servletfileupload upload=new servletfileupload(factory); 
//初始化解析器 
setupload(upload); 
//获取文件列表集合 
list<fileitem> list = upload.parserequest(request); 
//遍历 
for (fileitem items : list) { 
//判断 是不是普通表单个对象 
if(items.isformfield()){ 
//获取上传表单的name 
string fieldname=items.getfieldname(); 
//value 
string fieldvalue=items.getstring("utf-8"); 
//判断 
if("username".equals(fieldname)){ 
//设置 
upfile.setusername(fieldvalue); 
}else if("description".equals(fieldname)){ 
//设置属性 
upfile.setdescription(fieldvalue); 
} 
}else{ 
//是文件就准备上传 
//获取文件名 
string filename=items.getname(); 
//处理因为浏览器不同而导致的 获得 的 文件名的 差异 
int index=filename.lastindexof("\\"); 
if(index!=-1){ 
filename=filename.substring(index+1); 
} 
//生成随机的文件名 
string uuidname=generatefilename(filename); 
//获取上传的文件路径 
string savepath=request.getsession().getservletcontext().getrealpath("/web-inf/upload"); 
//获取请求对象中的输入流 
inputstream in = items.getinputstream(); 
//将文件打散存放在不同的路径,求出路径 
savepath=generaterandomdir(savepath,uuidname); 
//复制文件 
uploadfile(in,savepath,uuidname); 
string id=uuid.randomuuid().tostring(); 
upfile.setid(id); 
upfile.setsavepath(savepath); 
upfile.setuuidname(uuidname); 
upfile.setfilename(filename); 
//清除缓存 
items.delete(); 
} 
} 
}catch ( fileuploadbase.filesizelimitexceededexception e) { 
//抛出出异常 
throw e; 
} catch (fileuploadbase.sizelimitexceededexception e) { 
//抛出出异常 
throw e; 
}catch (fileuploadexception e) { 
e.printstacktrace(); 
} catch (unsupportedencodingexception e) { 
e.printstacktrace(); 
} catch (ioexception e) { 
e.printstacktrace(); 
} catch (exception e) { 
e.printstacktrace(); 
} 
return upfile; 
} 
/** 
* 初始化文件列表 
* @return 
*/ 
private static arraylist<string> initlist() { 
arraylist<string> list=new arraylist<string>(); 
list.add(".jpg"); 
list.add(".rar"); 
list.add(".txt"); 
list.add(".png"); 
return list; 
} 
/** 
* 复制文件 
* @param in items中的输入流 
* @param savepath 保存路径 
* @param uuidname 文件名 
*/ 
private static void uploadfile(inputstream in, string savepath, 
string uuidname) { 
//获取文件 
file file=new file(savepath, uuidname); 
outputstream out = null; 
try { 
int len=0; 
byte [] buf=new byte[1024]; 
//获取输出流 
out = new fileoutputstream(file); 
while((len=in.read(buf))!=-1){ 
out.write(buf, 0, len); 
} 
} catch (filenotfoundexception e) { 
e.printstacktrace(); 
} catch (ioexception e) { 
e.printstacktrace(); 
}finally{ 
try { 
in.close(); 
} catch (ioexception e) { 
e.printstacktrace(); 
} 
try { 
out.close(); 
} catch (ioexception e) { 
e.printstacktrace(); 
} 
} 
} 
/** 
* 生成随机的存放路径 
* @param savepath 保存路径 
* @param uuidname 生成的uuid名称 
* @return 
* 使用hashcode完成 
*/ 
private static string generaterandomdir(string savepath, string uuidname) { 
//转化为hashcode 
system.out.println("上传路径"+savepath); 
system.out.println("uuidname"+uuidname); 
int hashcode=uuidname.hashcode(); 
//容器 
stringbuilder sb=new stringbuilder(); 
while(hashcode>0){ 
//与上15 
int tmp=hashcode&0xf; 
sb.append("/"); 
sb.append(tmp+""); 
hashcode=hashcode>>4; 
} 
//拼接新的路径 
string path=savepath+sb.tostring(); 
system.out.println("path"+path); 
file file=new file(path); 
//判断路径存不存在 
if(!file.exists()){ 
//不存在就创建 
file.mkdirs(); 
} 
//返回保存路径 
return path; 
} 
/** 
* 生成新的文件名 
* @param uuidname 随机的id名字 
* @param filename 原来的名 
* @return 
*/ 
private static string generatefilename( string filename) { 
string uuidname=uuid.randomuuid().tostring(); 
return uuidname.replace("-", "").tostring()+"_"+filename; 
} 
/** 
* 初始化解析器 
* @param upload 
*/ 
private static void setupload(servletfileupload upload) { 
// 设置 字符编码 
upload.setheaderencoding("utf-8"); 
//设置文件大小 
upload.setfilesizemax(1024*1024*20); 
//设置总文件大小 
upload.setsizemax(1024*1024*50); 
//设置进度监听器 
upload.setprogresslistener(new progresslistener() { 
public void update(long pbytesread, long pcontentlength, int pitems) { 
system.out.println("已经读取: "+pbytesread+",总共有: "+pcontentlength+", 第"+pitems+"个"); 
} 
}); 
} 
/** 
* 工厂初始化方法 
* @param factory 
* @param tmp 缓冲目录 
*/ 
private static void setfactory(diskfileitemfactory factory, string tmp) { 
/// 配置初始化值缓冲区 
factory.setsizethreshold(1024*1024); 
file file=new file(tmp); 
//设置缓冲目录 
factory.setrepository(file); 
} 
}

二文件下载

servlet

public class downupfileservlet extends httpservlet { 
public void doget(httpservletrequest request, httpservletresponse response) 
throws servletexception, ioexception { 
dopost(request, response); 
} 
public void dopost(httpservletrequest request, httpservletresponse response) 
throws servletexception, ioexception { 
//获取id 
string id=request.getparameter("id"); 
//业务层的接口 
upfileservice upfileservice=new upfileserviceimpl(); 
//根据id查找这个对象 
upfile upfile=upfileservice.findupfilebyid(id); 
if(upfile==null){ 
return; 
} 
//获取文件的真实名称 
string filename=upfile.getfilename(); 
//如果文件名中有中文,需要转码,不然就下载时没有文件名 
filename=urlencoder.encode(filename, "utf-8"); 
//更改过的名称 
string uuidname=upfile.getuuidname(); 
//保存路径 
string savepath=upfile.getsavepath(); 
file file=new file(savepath,uuidname); 
//判断文件 是否存在 
if(!file.exists()){ 
request.setattribute("msg", "下载 的文件过期了"); 
request.getrequestdispatcher("/index").forward(request, response); 
return; 
} 
//设置文件下载响应头信息 
response.setheader("content-disposition", "attachement;filename="+filename); 
//使用io流输出 
inputstream in = new fileinputstream(file); 
servletoutputstream out = response.getoutputstream(); 
int len=0; 
byte [] buf=new byte[1024]; 
while((len=in.read(buf))!=-1){ 
out.write(buf, 0, len); 
} 
in.close(); 
} 
}

数据库

create database upload_download_exercise; 
use upload_download_exercise; 
create table upfiles( 
id varchar(100), //使用uuid生成 
uuidname varchar(255),//uuid加上原来的文件名 
filename varchar(100),//真实文件名 
savepath varchar(255),//保存路径 
uploadtime timestamp,//上传时间 
description varchar(255),//描述 
username varchar(10) 上传人 
); 

以上所述是小编给大家分享的java使用commos-fileupload实现文件上传与下载的相关内容,希望对大家有所帮助。