最近做文件下載的功能,大概就是下載一個excel模板,前端提交表單時,請求后台下載的controller。
前端的結構是有一個下載使用的表單,在html文件中,其中包含freemarker的標簽:
<div class="body-box"> <@p.form id="jvForm" action="v_import.do" labelWidth="12" class="form-inline" enctype="multipart/form-data" onsubmit="return false;"> <@p.td id="linkLogo" label="文件路徑"> <span id="ufc0" style="position:relative"> <input id='uploadFileText0' name="filepath" type='text' class="btn btn-default" size="14" readonly="true" /> <input id="uploadBrower" class="browse btn btn-default" type='button' value='瀏覽'/> <input id="uploadFile0" name="file" onchange="$('#uploadFileText0').val(this.value);" size="14" type="file" class="file-button btn btn-default"/> </span> <input id="uploadButton" class="upload-button btn btn-default" type="button" value="導入" /> <input id="templateButton" class="btn btn-default" type="button" value="模板下載" /><br/> <input id="success" type="hidden" value="${success!}" /> <input id="exceptionInfo" type="hidden" value="${exceptionInfo!''}" /> <input id="defaultExceptionInfo" type="hidden" value="導入失敗!" /> </@p.td> </@p.form> </div>
當點擊上邊'模板下載'按鈕時,提交表單,js邏輯為:
<script type="text/javascript"> $(function() { // 點擊下載模板 $("#templateButton").bind("click",function(){ downloadTemplate(); }); }); /* * 下載證書導入數據模板 */ function downloadTemplate() { var form = document.getElementById("jvForm"); form.action = "v_download_template.do"; form.encoding = "application/x-www-form-urlencoded"; form.submit(); } </script>
下載邏輯全部在后台,前台使用freemarker及html,下載使用的后台代碼:
controller:
@RequestMapping("/certificate_import/v_download_template.do")
public String downloadTemplate(HttpServletRequest request, HttpServletResponse response) {
log.info("下載證書導入模板...");
File template = cmsCertificateImportMng.getCertificateDataTemplate();
if (template == null) {
log.warn("沒有獲取到證書數據導入模板文件,下載失敗");
return;
}
// 將文件流寫入response
FileDownloadUtils.writeFile2Response(response, template);
}
FileDownloadUtils:
public static void writeFile2Response(HttpServletResponse response, File template) { response.setContentType("application/x-download;charset=UTF-8"); response.addHeader("Content-disposition", "filename=" + template.getName()); OutputStream os = null; ServletOutputStream ros = null; try { ros = response.getOutputStream(); os = new BufferedOutputStream(ros); byte[] bs = FileUtils.toByteArray(template); os.write(bs); os.flush(); ros.flush(); } catch (IOException e) { log.error("意外的異常:", e); } finally { if (os != null) { try { os.close(); } catch (IOException e) { log.error("意外的異常:", e); } } if (ros != null) { try { ros.flush(); ros.close(); } catch (IOException e) { log.error("意外的異常:", e); } } } }
這樣點擊下載按鈕,就能看到下載的文件:

本文的后台下載代碼是經過實際驗證的,能夠正常使用的,如有需要實現下載功能可以參考以上代碼。
