我需要读取服务器上的文件(在 Web 上不可用)并将其作为可下载文件输出给用户。
场景是
服务器上的文件可以是任何格式,例如 .pdf、.exe、.doc 等
这是在 SSJS 上完成还是在 Java 中完成都没有关系。
我真的很喜欢一些代码
最佳答案
这是我想出的代码,不是生产代码。
public static byte[] grabFile(String readFile) throws IOException {
File file = new File(readFile);
ByteArrayOutputStream ous = new ByteArrayOutputStream();
InputStream ios = new FileInputStream(file);
try {
byte []buffer = new byte[4096];
int read = 0;
while ( (read = ios.read(buffer)) != -1 ) {
ous.write(buffer, 0, read);
}
} finally {
try {
if ( ous != null )
ous.close();
} catch ( IOException e) {
}
try {
if ( ios != null )
ios.close();
} catch ( IOException e) {
}
}
return ous.toByteArray();
}
public static void download() throws IOException {
byte[] data = grabFile("\\\\server\\path\\to\\file.pdf");
HttpServletResponse response = (HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse();
response.reset();
response.setContentType("application/pdf");
response.setHeader("Content-disposition", "attachment; filename=\"filename.pdf\"");
OutputStream output = response.getOutputStream();
output.write(data);
output.close();
FacesContext.getCurrentInstance().responseComplete();
}
然后只需从 Xpage 的 beforeRenderResponse 中调用下载方法
关于java - 如何读取服务器文件并将其作为可下载文件在 XPage 的用户 Web 浏览器中输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14819257/