package com.mall.util; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.net.URLEncoder; public class FileUtil { private static final String CONTENT_TYPE = "application/x-msdownload;charset=UTF-8"; /* * 下载文件 */ public void doDownloadFile(String filePath, String filename, HttpServletRequest request, HttpServletResponse response) throws Exception { BufferedInputStream bis = null; BufferedOutputStream bos = null; try { long fileLength = new File(filePath).length(); filename = URLEncoder.encode(filename, "UTF-8"); response.reset(); response.setContentType(CONTENT_TYPE); response.setHeader("Content-Length", String.valueOf(fileLength)); response.addHeader("Content-Disposition","attachment; filename=\"" + filename + "\""); bis = new BufferedInputStream(new FileInputStream(filePath)); bos = new BufferedOutputStream(response.getOutputStream()); byte[] buff = new byte[2048]; int bytesRead; while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) { bos.write(buff, 0, bytesRead); } } catch (Exception e) { e.printStackTrace(); } finally { if (bis != null) bis.close(); if (bos != null) bos.close(); } } //删除目录底下的文件 public void doRemoveFile(String filepath){ try{ File file=new File(filepath); if(file.exists()){ boolean b=file.delete(); } }catch(Exception e){ e.printStackTrace(); } } }