zoukankan      html  css  js  c++  java
  • spring-mvc实现文件下载功能

    最近做文件下载的功能,大概就是下载一个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);
                          }
                    }
               }
         }

    这样点击下载按钮,就能看到下载的文件:

    本文的后台下载代码是经过实际验证的,能够正常使用的,如有需要实现下载功能可以参考以上代码。

  • 相关阅读:
    碰到一个在app内部浏览器锚点异常的问题
    常用js方法
    preg_match_all正则表达式的基本使用
    无线路由器WDS 桥接设置方法
    链表和数组的区别在哪里?
    php报错: PHP Warning: PHP Startup: memcache: Unable to initialize module
    mysql修改密码
    快速排序
    vuex到底是个啥
    vue实现简单表格组件
  • 原文地址:https://www.cnblogs.com/xhj123/p/12398713.html
Copyright © 2011-2022 走看看