如何将xml编码为Base64并作为servlet响应发回?

时间:2012-05-03 07:55:51

标签: servlets groovy base64

我写了一个servlet(扩展名为.groovy),它应该以Base64编码

返回xml
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    String fileName=(String) request.getParameter("fileName")

    if (fileName == null || fileName.equals(""))throw new ServletException("Invalid or non-existent file parameter in SendXml servlet.")
    if (fileName.indexOf(".xml") == -1)fileName = fileName + ".xml"

    System.out.println(fileName)

    try {

      String relativeWebPath = "/WEB-INF/classes/com/abc/csm/xml/"+fileName
      String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath)

      String fileContents=new File(absoluteDiskPath).text
      response.setContentType("text/xml")
      response.addHeader("Content-Disposition", "attachment filename="+ fileName)

      XmlHandler xm=new XmlHandler()

      PrintWriter out = response.getWriter()
      String enxml=xm.encodeBase64(fileContents)
      response.setContentLength((int) enxml.length)

      out.println(enxml)
      out.close()
      out.flush()
    } catch (Exception e) {       println e     } 
}

XmlHandler encodeBase64方法

def encodeBase64(String text) {
    return new String(Base64.encodeBase64(text.getBytes()))
}

但我想有些东西不见了。请帮忙

更新

另外请注释是否是从包中访问文件的正确方法?

1 个答案:

答案 0 :(得分:3)

您可以替换:

  String enxml=xm.encodeBase64(fileContents)

  String enxml = fileContents.bytes.encodeBase64()

或者,最好将编码传递给getBytes的调用:

  String enxml = fileContents.getBytes( 'UTF-8' ).encodeBase64()

此外,我相信您在标题中attachment后错过了分号...该行应为:

  response.addHeader( "Content-Disposition", "attachment; filename=$fileName" )

编辑,编码和解码示例:

编码:

String encoded = "tim_yates".getBytes( 'UTF-8' ).encodeBase64()

解码:

String original = new String( encoded.decodeBase64(), 'UTF-8' )
assert original == 'tim_yates'