给客户做的一个公司的小网站,客户提出需要下载的用户需要通过邮件向他们申请KEY,才可以下载。我在后台做了一个简单的KEY生成的工具,其实就是一个简单的hibernate生成UUID的程序,就拿这个UUID来作为KEY.在用户下载的时候需要输入一个KEY,通过验证之后才能下载,跟普通的图片验证没什么区别,可能只是一个在服务器端一个在客户端验证的区别,当然图片也可以在服务器端验证。下面上代码:
页面代码:
<div class="proList">
KEY:<input type="text" name="id" id="id" value="" size="32"/>
<%ArticleBean articleBean= (ArticleBean)request.getAttribute("articleBean");%>
<%if(articleBean.getAttachList().size()>0 ){%><DIV></DIV><%} %>
<%for(AttachmentBean attachmentBean:articleBean.getAttachList()){ %>
<DIV> <A href="javascript:verifyKey('<%=CONTEXT_PATH %>/download.action?fileName=<%=attachmentBean.getFileNameURL() %>&filePath=<%=attachmentBean.getName()%>');"><%=attachmentBean.getFileName() %></A></DIV>
<%} %>
</div>
JS代码:
function verifyKey(url){ var id = $("#id").val(); var curl = "<%=CONTEXT_PATH %>/cmsAdmin/downloadkey/verifyKey.action"; $.ajax({ url:curl, data:"id="+id, dataType: "json", success: function(json){ if(json.status==1){ window.location.href=url; }else{ alert("请输入正确的KEY,若没有请向unisec@mail.uni-sec.com申请!"); } } }); }
服务器端代码,基于struct2的:
public String download() {
try {
File input = null;
String classpath = DownloadAction.class.getResource("/").getPath();
String savePath = classpath.replaceAll("/WEB-INF/classes/",
"/upload/")
+ this.filePath;
input = new File(savePath);
docStream = new FileInputStream(input);
this.contentDisposition = Utils.chgStr(this.fileName);
return "download";
} catch (Exception e) {
log.error("Cannot execute an SWorkAction filedown action: " + e, e);
return ERROR;
}
}
action的xml配置文件:
<action name="download" class="cn.net.tech.web.action.DownloadAction" method="download"> <result name="download" type="stream"> <param name="contentType"> application/octet-stream </param> <param name="inputName">docStream</param> <param name="bufferSize">1024</param> <param name="contentDisposition"> attachment;filename="${contentDisposition}" </param> </result> <result name="error">/pages/Error.jsp</result> </action>