Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
534 views
in Technique[技术] by (71.8m points)

java - Is it possible to download a binary file from JSP?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();
%>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...