Created
January 18, 2012 09:52
-
-
Save yongboy/1632237 to your computer and use it in GitHub Desktop.
DownloadFileWithNginxAction.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.servlet3.demo; | |
import java.io.IOException; | |
import java.io.Writer; | |
import javax.servlet.ServletException; | |
import javax.servlet.annotation.WebServlet; | |
import javax.servlet.http.HttpServlet; | |
import javax.servlet.http.HttpServletRequest; | |
import javax.servlet.http.HttpServletResponse; | |
import org.apache.commons.io.FilenameUtils; | |
import org.apache.commons.lang.StringUtils; | |
import org.apache.log4j.Logger; | |
/** | |
* 控制检测用户具有权限下载文件,转交给ngxin处理 | |
* | |
* @author yongboy | |
* @time 2012-1-18 | |
* @version 1.0 | |
*/ | |
@WebServlet("/download") | |
public class DownloadFileWithNginxAction extends HttpServlet { | |
private static final long serialVersionUID = 1L; | |
private final Logger log = Logger | |
.getLogger(DownloadFileWithNginxAction.class); | |
protected void doGet(HttpServletRequest request, | |
HttpServletResponse response) throws ServletException, IOException { | |
String filePath = request.getParameter("path"); | |
boolean right = checkRight(filePath); | |
if (!right) { | |
output(response, "您的下载有误!"); | |
return; | |
} | |
// 下面文件处理下载文件时,是不需要编码的,不会出现中文乱码问题 | |
String fileName = FilenameUtils.getName(filePath); | |
response.setHeader("Content-Type", "application/octet-stream"); | |
response.setHeader("Content-disposition", "attachment; filename=" | |
+ fileName); | |
// 当前用户符合下载要求,转发给Nginx进行下载处理 | |
response.setHeader("X-Accel-Redirect", "/downloads/" + filePath); | |
response.setHeader("X-Accel-Charset", "utf-8"); | |
log.debug("send to nginx to handle file download ..."); | |
} | |
/** | |
* 下载逻辑的简单实现版本 | |
* | |
* @author yongboy | |
* @time 2012-1-18 | |
* | |
* @param path | |
* @return | |
*/ | |
private boolean checkRight(String path) { | |
if (StringUtils.isBlank(path)) { | |
return false; | |
} | |
return true; | |
} | |
private static void output(HttpServletResponse response, String message) { | |
try { | |
response.setContentType("text/html; charset=UTF-8"); | |
Writer out = response.getWriter(); | |
out.write(message); | |
out.flush(); | |
out.close(); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment