gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 18:22:10 26 4
gpt4 key购买 nike

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

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

更新

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

最佳答案

您可以更换:

  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'

关于servlets - 如何将 xml 编码为 Base64 并作为 servlet 响应发回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10427295/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com