我正在使用JAXB来创建XML文件。我想在用户的PC上下载文件。 这是我的代码,实际上是在向服务器创建文件:
OutputStream file = new FileOutputStream("E:\\"+n+".xml");
JAXBContext jaxbContext = JAXBContext.newInstance(F6005.class);
javax.xml.bind.Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, new Boolean(true));
jaxbMarshaller.marshal(f6005, file);
getServletContext().getRequestDispatcher("/F6207done.jsp").forward(request, response);
相反,我想在点击“下载”按钮后将文件发送到用户文件夹。我该怎么办?
答案 0 :(得分:1)
从响应中请求OutputStream。更改内容类型并发送数据。浏览器将以所描述的格式呈现文件。
OutputStream os = response.getOutputStream();
response.setContentType("text/xml; charset=UTF-8");
jaxbMarshaller.marshal(f6005, os);
答案 1 :(得分:0)
我找到了解决方案,万一有人需要它:
response.setHeader("Content-Disposition", "attachment; filename="+nn+".xml");
response.setContentType("text/xml; charset=UTF-8");
OutputStream outStream = response.getOutputStream();
javax.xml.bind.Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, new Boolean(true));
jaxbMarshaller.marshal(f6005, outStream);