我写了一个servlet(扩展名为.groovy),它应该以Base64编码
返回xmlprotected 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()))
}
但我想有些东西不见了。请帮忙
更新
另外请注释是否是从包中访问文件的正确方法?
答案 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'