本文介绍了JSP下载 - 应用程序/八位字节流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在JSP中有一个页面,其中列出了一些用户可以下载的文件。
Thoses文件不在本地服务器上,它们位于远程文件服务器上。

I have a page in JSP that list some file that could be downloaded by a user.Thoses files are not on the local server, they are on a remote file server.

当用户单击下载文件时,Web服务器通过TCP连接到文件服务器。 Web服务器下载文件并为客户端创建HTTP响应。

When the user click to download a file, the webserver connect via TCP to the file server. The web server download the file and create a HTTP response for the client.

这是我的代码:

<%@page language="java"%>
<%@page import="sun.misc.Request"%>
<%@page import="listing.ClientTCPStockage"%>
<%@page import="java.net.InetAddress"%>

<%
out.clearBuffer();

String nomFichier = request.getParameter("fichier");
String adresseStockage = request.getParameter("adresseStockage");

ClientTCPStockage clientStockage = new ClientTCPStockage(InetAddress.getByName(adresseStockage), 2004);
byte donneeFichier[] = clientStockage.getDonneesFichier(nomFichier);

response.setHeader("Content-Disposition", "attachment;filename=\"" + nomFichier + "\"");
response.setHeader("Content-Type", "application/octet-stream;");
response.setHeader("Accept-Ranges", "bytes");
response.setHeader("Content-Length", String.valueOf(donneeFichier.length));

for(int i = 0; i < donneeFichier.length; i++){
    out.write(donneeFichier[i]);
}
%>

对于基于文本的文件,如.csv或正常的.txt
但它不适用于其他类型,如.mp3或.jpeg ..文件最终损坏。

This is working perfectly fine for text-based file, like .csv or normal .txtbut It doesnt work for other type like .mp3 or .jpeg.. the files end up corrupt.

我认为我的编码有问题,但我可以' t找到哪里..

I think there is a problem with my encoding but I can't find where..

这是HTTP头响应:

HTTP/1.x 200 OK
Server: Apache-Coyote/1.1
Content-Disposition: attachment;filename="test.mp3"
Accept-Ranges: bytes
Content-Type: application/octet-stream;
Content-Length: 5387668
Date: Sun, 20 Dec 2009 18:52:18 GMT

谢谢。

推荐答案

如果强制使用jsp(而不是servlet),可以看一下

If forced to use jsp (and not a servlet), you may take a look at this how-to

它使用 ServletOutputStream ,它更适合二进制内容,而不是一个 JspWriter

It uses the ServletOutputStream, which is more appropriate for binary content, rather than a JspWriter.

另请注意修剪空白的设置。

Also note the settings for trimming the whitespaces.

这篇关于JSP下载 - 应用程序/八位字节流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 19:36