Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
492 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...