2

我写了一个 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()))
}

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

更新

另外请评论从包中访问文件的正确方法是什么?

4

1 回答 1

4

您可以更换:

  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'
于 2012-05-03T08:13:57.193 回答