是否可以从JSP下载二进制文件?

时间:2022-06-15 01:23:52

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 )

我没有直接使用servlet的可能性,所以我*使用JSP(历史悠久,时间短,你不想听)

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.

不要过分关注代码。它只显示了这个想法。它将旁路数组写入jsp输出流。

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

可能吗?听起来合理吗?是否有JSTL或其他已经处理过的东西?

1 个解决方案

#1


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

是的,使用“application / octet-stream”获取通用二进制数据。并从导入标记和scriptlet周围删除每个换行符/空格。

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

#1


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

是的,使用“application / octet-stream”获取通用二进制数据。并从导入标记和scriptlet周围删除每个换行符/空格。

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