综合开发
一,文件的上传
Upload.java,由该servlet 实现文件的上传及文件信息存储到数据库。
package com.ayit.upload;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.SQLException;
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.dbutils.QueryRunner;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import com.ayit.bean.FileInfo;
import com.ayit.utils.JDBCUtils;
import com.ayit.utils.UploadUtils;
/**
* 实现文件上传操作
* @author XiaYuJia
*
*/
public class Upload extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
//创建磁盘文件工厂
DiskFileItemFactory factory = new DiskFileItemFactory();
//创建核心上传类
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("utf-8");
//解析request对象
List<FileItem> list = upload.parseRequest(request);
//创建FileInfo对象
FileInfo fileInfo = new FileInfo();
//遍历集合
for (FileItem fileItem : list) {
//判断是否是普通输入项
if(fileItem.isFormField()){
String description = fileItem.getString("utf-8");
fileInfo.setDescription(description);
}else{
//文件上传项
//获取文件路径并截取文件名称
String filename = fileItem.getName();
int lens = filename.lastIndexOf("\\");
if(lens!=-1){
filename = filename.substring(lens+1);
}
//得到随机字符串
String uuid = UUID.randomUUID().toString();
String uuidname = uuid+"_"+filename;
//得到文件夹的完全路径
String realPath = getServletContext().getRealPath("/resource");
//得到分离的路径
String url = UploadUtils.getPath(uuidname);
//判断文件夹是否存在
String savepath = realPath + url;
File file = new File(savepath);
if(!file.exists()){
file.mkdirs();
}
//得到上传文件
InputStream in = fileItem.getInputStream();
//使用文件输出流写到写文件夹里面
OutputStream out = new FileOutputStream(savepath+"/"+uuidname);
//流对接
int len = 0;
byte[] b = new byte[1024];
while((len = in.read(b))!=-1){
out.write(b,0,len);
}
out.close();
in.close();
//设置上传信息
fileInfo.setUuidname(uuidname);
fileInfo.setRealname(filename);
fileInfo.setSavepath(savepath);
}
}
//把数据存到数据库
QueryRunner runner = new QueryRunner(JDBCUtils.getDataSource());
Object[] os = {fileInfo.getUuidname(),fileInfo.getRealname(),fileInfo.getSavepath(),fileInfo.getDescription()};
runner.update("insert into resource values(null,?,?,?,?)",os);
response.getWriter().write("success");
} catch (Exception e) {
throw new RuntimeException("上传失败");
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}
二,文件的下载
1,listServlet获取所有文件信息
package com.ayit.upload;
import java.io.IOException;
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.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import com.ayit.bean.FileInfo;
import com.ayit.utils.JDBCUtils;
/**
* 查询数据库中所有文件信息
* @author XiaYuJia
*
*/
public class ListServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//查询数据库,并把bean设置到域里面,在页面显示出来
try{
QueryRunner runner = new QueryRunner(JDBCUtils.getDataSource());
String sql = "select * from resource";
BeanListHandler<FileInfo> blh = new BeanListHandler<FileInfo>(FileInfo.class);
List<FileInfo> list = runner.query(sql, blh);
request.setAttribute("list", list);
request.getRequestDispatcher("/list/list.jsp").forward(request, response);
}catch(Exception e){
throw new RuntimeException("查询失败");
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}
2,list.jsp
<body>
<table width="80%" align="center" border="1" cellspacing="0">
<caption><font size="6"><b>文件目录</b></font></caption>
<tr>
<th>ID</th>
<th>FileName</th>
<th>Description</th>
</tr>
<c:forEach var="list" items="${list }">
<tr align="center">
<td>${list.id }</td>
<td><a
href="${pageContext.request.contextPath }/Download?id=${list.id}">${list.realname
}</a>
</td>
<td>${list.description }</td>
</tr>
</c:forEach>
</table>
</body>
3,download实现文件下载功能
package com.ayit.upload;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import sun.misc.BASE64Encoder;
import com.ayit.bean.FileInfo;
import com.ayit.utils.JDBCUtils;
/**
* 实现文件下载功能
* @author XiaYuJia
*/
public class Download extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//获取文件id
String id = request.getParameter("id");
//通过id查询数据库返回文件信息
try{
QueryRunner runner = new QueryRunner(JDBCUtils.getDataSource());
BeanHandler<FileInfo> bh = new BeanHandler<FileInfo>(FileInfo.class);
String sql = "select * from resource where id=?";
FileInfo fileInfo = runner.query(sql, bh,id);
//判断文件是否为空
if(fileInfo==null){
throw new RuntimeException("文件不存在");
}else{
//获取文件信息
String realname = fileInfo.getRealname();
String uuidname = fileInfo.getUuidname();
String savepath = fileInfo.getSavepath();
//得到当前请求的额浏览器类型
String header = request.getHeader("User-Agent");
//如果是火狐浏览器
if(header.contains("Firefox")) {
//base64编码
realname = "=?UTF-8?B?"+
new BASE64Encoder().encode(realname.getBytes("utf-8"))+"?=";
} else {//ie浏览器
realname = URLEncoder.encode(realname,"utf-8");
}
//实现文件下载操作
//设置mime类型
String mimeType = getServletContext().getMimeType(realname);
response.setContentType(mimeType);
//设置下载头
response.setHeader("Content-Disposition", "attactment;filename="+realname);
//从服务器获取文件输入流
InputStream in = new FileInputStream(savepath+"/"+uuidname);
//使用输出流写到浏览器
OutputStream out = response.getOutputStream();
//流对接
int len = 0;
byte[] b = new byte[1024];
while((len=in.read(b))!=-1){
out.write(b,0,len);
}
in.close();
}
}catch(Exception e){
throw new RuntimeException("下载失败");
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}