Is it possible to download a binary file from JSP?

你。 提交于 2019-11-28 10:46:32

问题


I think is it quite possible, but I'm not sure.

I don't have the possibility to use servlet directly, so I'm forced to use JSP ( long history, short time, you don't want to hear )

So I think something like the following will do:

// PSEUDO-CODE:
// source.jsp
Download your file
<a href="file.jsp?xyz">MyDocument.doc</a>


// file.jsp
<%@page content-type="applicaton/somethig-binary-xyz"%>
byte[] data = getBinaryFromSomeWhere();

int start = 0;
int end = data.length < 1024 ? data.length : 1024;
int written = 0;
while( written < data.length ) {
    out.write( data, start, end );
    writtern += end;
    start = end;
    end += written + data.length < 1024 ? data.length : 1024;
}

%>

Don't put too much attention to the code. It only shows the idea. It writes the bynary array to the jsp output stream.

Is it possible? Does it sounds reasonable? Is there a JSTL or other thing that already handles that?


回答1:


Yes, use "application/octet-stream" for generic binary data. And remove every line break/whitespace from the import tags and around the scriptlets.

<%@ page contentType="applicaton/octet-stream" %><%
byte[] data = getBinaryFromSomeWhere(request.getParameter("xyz"));
response.setHeader("Content-length", Integer.toString(data.length));
response.setHeader("Content-Disposition", "attachment; filename=xyz.bin");
response.getOutputStream().write(data, 0, data.length);
response.getOutputStream().flush();
%>


来源:https://stackoverflow.com/questions/1133920/is-it-possible-to-download-a-binary-file-from-jsp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!