第一次使用servlet下载,写个demo留着以后参考.代码如下:
public Result downloadFile(HttpServletRequest request,
HttpServletResponse response) {
String target = request.getParameter("target");
File file = new File(FileUtil.MeeStorage + target);
if (!file.exists())
return null;
if (file.exists()) {
try {
response.setContentType("application/octet-stream");
response.setCharacterEncoding("GB2312");
String fname = new String(file.getName().getBytes("GBK"),"ISO8859-1");//防止中文乱码
doDownload(request, response, file);
} catch (Exception e) {
e.printStackTrace();
}
}
return new Result(Type.download, null, "/WEB-INF/fileIndex.jsp", true);
}
private void doDownload(HttpServletRequest req, HttpServletResponse resp,
File file) throws IOException {
int length = 0;
ServletOutputStream op = resp.getOutputStream();
ServletContext context = (ServletContext)req.getAttribute("ServletContext");//serlet中的getServletConfig().getServletContext(),这里封装了一下
String mimetype = context.getMimeType(file.getPath());
resp.setContentType((mimetype != null) ? mimetype
: "application/octet-stream");
resp.setContentLength((int) file.length());
resp.setHeader("Content-Disposition", "attachment; filename=\""
+ file.getName() + "\"");
byte[] buffer = new byte[4096];
DataInputStream in = new DataInputStream(new FileInputStream(file));
while ((in != null) && ((length = in.read(buffer)) != -1)) {
op.write(buffer, 0, length);
}
in.close();
op.flush();
op.close();
}