【问题标题】:cannot export excel when parameter contains '#',why?当参数包含'#'时无法导出excel,为什么?
【发布时间】:2016-05-27 16:42:58
【问题描述】:
@RequestMapping(value=ClientAdminUrl.my_excel_report, method = RequestMethod.GET)
public void getExcelReport(String userId, String shortDates, Model model,
        final HttpServletResponse response, final HttpServletRequest request){
    String reportFilePath = SiteConfig.getSiteConfigProp(MY_REPORT_PATH);
    String userReportPath = reportFilePath + File.separator + userId+ File.separator;       
    String myExcelReportPath = userReportPath + userId+System.currentTimeMillis() + File.separator;

    UserInfo userInfo = userInfoService.selectByPrimaryKey(userId);
    String userName = userInfo.getUserName();



    String fileName = "report_"+userName+".zip";    
    String reportZipFile = myExcelReportPath + File.separator+ fileName;
    String zipFileRootPath = "my Report";           
    makeExcelReportPathDirectory(myExcelReportPath);
    for(String date: shortDates.split(",")) {
        generateExcel(userId, Integer.parseInt(date), myExcelReportPath, userName);
    }

    try {
        CompressUtils.packToolFiles(myExcelReportPath, zipFileRootPath, reportZipFile);
    } catch (IOException e) {
        LOGGER.error("failed to zip excel.");
    }

    InputStream is = null;
    try {
        is = new FileInputStream(reportZipFile);
        int contentLength = is.available();
        response.setContentType("application/octet-stream");
        response.setContentLength(contentLength);
        response.setHeader("Content-Disposition", "attachment; filename="+fileName);
        IOUtils.copy(is, response.getOutputStream());
        response.flushBuffer();
    } catch (IOException e) {
        e.printStackTrace();
    }finally{
        if(is!=null){
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

现在跟随 javascript 块:

    function doExport(){
    var obj = $('#DetailTbody input[name="checkbox"]');     
    if(obj.size() == 0){
        return;
    }
    var userId = null;
    var shortDates = '';
    $.each(obj,function(i) {
        if($(this).is(":checked")) {
            userId = $(this).val();
            if(shortDates == '') {
                shortDates += $(this).parents("tr").children().eq(0).text();
            }else {
                shortDates += ',' + $(this).parents("tr").children().eq(0).text();
            }               
        }
    }); 
    if(userId == null || userId == '' || userId == 'undefined'){
        $.messager.alert('Message',$.i18n.prop("my.log.export.alert.message"));
        return;
    }
    //start export
    window.location.href = contextPath +  "/clientAdmin/my/report/excel?userId="+userId + "&shortDates="+shortDates;
}

当我尝试导出excel,调试时,发现如果userId包含'#',例如'user#123',那么java代码,userid出来是'user',后面的字'#' 全部删除。参数 shortDates 为空。

关于foxfire的空间问题,解决方法如下: java代码:

private void 下载(HttpServletRequest 请求,HttpServletResponse 响应)抛出 UnsupportedEncodingException { String fileName = "我的下载测试文件";

    String encoding = request.getParameter("code");
    if ((encoding == null) || (encoding == "undefined")) {
      encoding = "utf-8";
    }
    fileName = Utils.urlDecoder(fileName, new String[] { encoding });
    System.out.println(fileName);

    String[] dots = fileName.split("[.]");
    String postfix = dots[(dots.length - 1)];

    if (postfix != null) {
      if (("xls".equals(postfix)) || ("xlsx".equals(postfix))) {
        response.setContentType("application/msexcel");
      }
      else if (("doc".equals(postfix)) || ("docx".equals(postfix))) {
        response.setContentType("application/msword");
      }
      else if (("zip".equals(postfix)) || ("rar".equals(postfix))) {
        response.setContentType("application/zip");
      }
      else if (("gif".equals(postfix)) || ("jpg".equals(postfix)) || ("png".equals(postfix)) || ("jpeg".equals(postfix))) {
        response.setContentType("image/gif");
      }
      else if ("pdf".equals(postfix)) {
        response.setContentType("image/pdf");
      }
      else
        response.setContentType("application/text");
    }
    response.setHeader("Content-disposition", "attachment;filename=" + fileName);
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    try {
      bis = new BufferedInputStream(new FileInputStream(REAL_PATH + fileName));
      bos = new BufferedOutputStream(response.getOutputStream());
      byte[] buff = new byte[2048];
      int bytesRead;
      while (-1 != (bytesRead = bis.read(buff, 0, buff.length)))
      {
        bos.write(buff, 0, bytesRead);
      }
    } catch (Exception localException) {
    } finally {
      try {
        bos.flush();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }

解决这个问题只需要改变这一行:

response.setHeader("Content-disposition", "attachment;filename=\"" + fileName +"\"");

【问题讨论】:

标签: java spring-mvc firefox parameters


【解决方案1】:

在 URL 中,# 字符用于哈希部分的开头。此字符后面的所有内容都是“仅限客户端”,不会发送到服务器。

您必须引用此字符,在您的 javascript 代码中将 # 替换为 %23

你可以使用javascript函数encodeURIComponent

window.location.href = contextPath +
  "/clientAdmin/my/report/excel?userId=" + encodeURIComponent(userId) +
  "&shortDates=" + encodeURIComponent(shortDates);

【讨论】:

  • thx!这是你的意思吗23'?对不起,我不是说英语的人,我有点难以表达我的意思......
  • 我已经更新了我的答案,向您展示如何在 javascript 中引用 url
  • 这很有帮助。# 问题已解决,但当它包含 空格时仍然存在问题。因为我编写此代码用于导出excel,空格字符已经被'%20'编码了,但是当我尝试导出excel时,它只能得到一个文件-----一个未知类型的文件,这个问题只在foxfire上显示,但chorme还可以。
  • 我已经解决了这个问题。并更新了我的问题 text.thx
  • 很抱歉现在不能给你投票,因为我是新来的。当我获得资格时,会这样做。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-08-13
  • 2018-07-17
  • 2012-12-10
  • 1970-01-01
  • 1970-01-01
  • 2012-03-07
  • 2015-09-13
相关资源
最近更新 更多