上传的类:
public class UploadServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
/*
* 1. 上传三步
* * 得到FileItem对象
*/
// 创建工厂
DiskFileItemFactory factory = new DiskFileItemFactory();
// 创建解析器
ServletFileUpload sfu = new ServletFileUpload(factory);
try {
// 解析request,得到FileItem
FileItem fi = (FileItem)sfu.parseRequest(request).get(0);
/*
* 2. 保存上传文件
*/
/*
* 2.1 得到保存路径
*/
String savepath = this.getServletContext().getRealPath("/WEB-INF/files");
/*
* 2.2 得到文件名称路径
* * 处理客户端完整路径问题
* * 处理中文乱码问题
* * 处理同名问题
*/
String filename = fi.getName();// 得到文件名
// 处理完整路径问题
int index = filename.lastIndexOf("\\");
if(index != -1) {
filename = filename.substring(index+1);
}
// 处理同名问题
String realname = CommonUtils.uuid() + "_" + filename;
/*
* 2.3 保存文件
* * 使用savepath + realname,得到目标文件!
* * 调用fileItem的write()方法完成保存
*/
File destFile = new File(savepath, realname);
fi.write(destFile);
/*
* 3. 创建MyFile对象,保存到数据库
*/
MyFile mf = new MyFile();
mf.setFid(CommonUtils.uuid());//设置主键
mf.setFsize(fi.getSize());//设置文件字节数
mf.setFname(filename);//设置显示名
mf.setFpath(destFile.getAbsolutePath());//设置文件的保存路径
mf.setCnt(0);//设置下载次数
mf.setUploadtime(String.format("%tF %<tT", new Date()));//设置上传时间
MyFileService myFileService = new MyFileService();//创建service
myFileService.add(mf);//向数据库保存数据
response.getWriter().print("恭喜,上传成功了!");
} catch(Exception e) {
throw new RuntimeException(e);
}
}
}
下载:
public String download(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/*
* 1. 获取fid
* 2. 使用fid调用service方法,得到MyFile对象(直接路径,显示名称)
* 3. 一个流两个头
* 4. 修改下载次数
*/
String fid = request.getParameter("fid");
MyFile myfile = myFileService.load(fid);
/*
* 一个流,两个头
*/
// 通过文件保存的路径,创建流
InputStream input = new FileInputStream(myfile.getFpath());
// 通过文件名称获取mime类型
response.setContentType(this.getServletContext().getMimeType(myfile.getFname()));
// 设置content-disposition
// 获取文件名称,处理下载框中编码问题
String fname = new String(myfile.getFname().getBytes("GBK"), "ISO-8859-1");
// 设置响应头
response.setHeader("Content-Disposition", "attachment;fileName=" + fname);
/*
* 把流中的数据写给浏览器
*/
IOUtils.copy(input, response.getOutputStream());
/*
* 修改下载次数
*/
myfile.setCnt(myfile.getCnt() + 1);
myFileService.updateCnt(myfile);
return null;
}
}