1

我正在使用 JAXB 生成一个 xml 文件,但目前文件是在指定位置生成的,如何使用浏览按钮指定文件夹的位置来保存生成的文件。已尝试使用 HTML 的 input type="file",但它对于上传文件很有用。希望它仅从富人脸中进行。

4

1 回答 1

1

Content-Disposition只需将其与值为.的标头一起直接写入 HTTP 响应即可attachment。这将强制浏览器弹出“另存为”对话框。

因此,基本上您需要做的就是在设置正确的标头后将 XML 树直接编组到HTTP 响应的输出流,而不是文件的输出流。

FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext ec = fc.getExternalContext();
// ...

ec.responseReset(); // Make sure the response is clean and crisp.
ec.setResponseContentType("text/xml"); // Tell browser which application to associate with obtained response.
ec.setResponseCharacterEncoding("UTF-8"); // Tell browser how to decode the characters in obtanied response.
ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // Tell browser to pop "Save As" dialogue to save obtained response on disk.
marshaller.marshal(model, ec.getResponseOutputStream()); // Look ma, just marshal JAXB model straight to the response body!
fc.responseComplete(); // Tell JSF that we've already handled the response ourselves so that it doesn't need to navigate.

注意:无法通过 ajax 下载文件。记得关闭调用此方法的 RichFaces/Ajax4jsf 命令组件的 ajax 功能(如果有)。

也可以看看:

于 2013-04-10T14:53:58.343 回答