文件上传与下载
1. 上传
控制层处理
//文件上传请求控制
/*
* 从Servelt3.0开始Servlet对文件上传做了增强
* 使用 @MultipartConfig 配置Servlet 可以通过 getPart直接获得文件对象
*
* */
@MultipartConfig
@WebServlet("/pic.do")
public class UserPicController extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpUtils2.setUTF8(req,resp);
//获得上传的文件对象
Part part = req.getPart("picfile");
String eid= req.getParameter("eid");
System.out.println(eid);
//确定一个保存的路径
String path= this.getServletContext().getRealPath("/upload");
File uploadDir = new File(path);
if(!uploadDir.exists()){
uploadDir.mkdirs();
}
//细节2: 做类型的判断
java.util.List<String> nameList = new ArrayList<String>();
nameList.add(".jpg");
nameList.add(".bmp");
nameList.add(".png");
String filename = part.getSubmittedFileName();
String extName = filename.substring(filename.lastIndexOf("."));
if(!nameList.contains(extName)) {
resp.getWriter().println("上传失败,请上传 jpg bmp png");
return;
}
String abspath = null;
//把文件上传到uploadDir下
if(part!=null){
//细节3:调用生成散列目录方法,防止一个文件夹中文件太多
String newpath = NewFilePath(uploadDir.getAbsolutePath(), part.getSubmittedFileName());
abspath = newpath+File.separator+ UUID.randomUUID().toString().replace("-","") +part.getSubmittedFileName();
part.write( abspath );
}
resp.getWriter().println("上传完成");
//修改数据库 id path abspath
EmpService empService = new EmpServiceImpl();
int row = empService.updatePic( eid,abspath.substring( abspath.indexOf("\\upload") ) );
if(row>0){
resp.sendRedirect("/findByPage.do");
}
}
//生成散列目录
public static String NewFilePath(String basePath,String filename){
int hashcode = filename.hashCode();
int path1 = hashcode&15;//与运算 0~15 二级
int path2 = (hashcode>>4)&15;//与运算 0~15 三级
String dir = basePath+"\\"+path1+"\\"+path2;//与一级目录拼接一起
File file = new File(dir);//创建文件夹对象
if(!file.exists()){//不存在则新建
file.mkdirs();
}
return dir;//返回新路径
}
}
视图层
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form method="post" enctype="multipart/form-data" action="/pic.do">
<input name="eid" type="hidden" value="${param.id}">
<input name="picfile" type="file">
<input type="submit" value="上传">
</form>
</body>
</html>
注意:
文件上传的form表单必须要用 enctype=“multipart/form-data”
控制层加注解@MultipartConfig,也可以写配置文件
2. 下载
控制层
//文件下载列表的控制
@WebServlet("/file/list.do")
public class FileDownloadListController extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpUtils2.setUTF8(req,resp);
//获得 网站相对路径的觉得路径
String path = this.getServletContext().getRealPath("/WEB-INF/download");
File dir = new File(path);
//获得绝对路径的File对象,下的子文件
String[] names = dir.list();
for(String fileName : names){
resp.getWriter().println(fileName+"<a href='/file/download.do?d_file="+fileName+"'>下载</a>");
}
}
}
//文件下载控制器 根据请求的文件名字下载内容
@WebServlet("/file/download.do")
public class FileDownloadController extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//HttpUtils2.setUTF8(req,resp);
//1. 获得下载的文件名字
String fileName = req.getParameter("d_file");
//2. 在下载目录文件夹下找到文件
String dir = this.getServletContext().getRealPath("/WEB-INF/download/");
//3. 设置响应头,浏览器才知道这个一个文件,浏览器会弹出下载对话框
resp.setHeader("content-disposition", "attachment;filename="+ URLEncoder.encode(fileName,"utf-8" ));
//4 .读取下载文件
FileInputStream fis = new FileInputStream( dir+fileName );
byte[] bs = new byte[1024];
int len;
while( (len=fis.read(bs))>0 ){
//写到到客户端
resp.getOutputStream().write(bs,0,len);
}
//5. 下载完成
fis.close();
}
}
注意:
文件下载要设置响应头:
resp.setHeader(“content-disposition”, “attachment;filename=”