我有这段代码可以从jsf下载文件。它工作正常,但下载的文件中缺少最后四个字节(utf中包含两个字符)。
由于我在getBytes()中添加了“ UTF-8”,因此出现了
文本是json字符串。如果我在文本中添加四个空格字符,它将完全正常工作。
public void download() throws IOException {
String txt = getText();
FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext ec = fc.getExternalContext();
String fileName = "engineData.json";
ec.responseReset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
ec.setResponseContentType("application/json"); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ExternalContext#getMimeType() for auto-detection based on filename.
ec.setResponseContentLength(txt.length()); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.
try (OutputStream output = ec.getResponseOutputStream()) {
output.write(txt.getBytes("UTF-8"));
// Now you can write the InputStream of the file to the above OutputStream the usual way.
// ...
output.flush();
}
fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}