简体   繁体   English

使用 servlet 下载 txt 文件

[英]Download a txt file using a servlet

I'm trying to make a html button which downloads a file from a server into the user's machine with a servlet .我正在尝试制作一个 html 按钮,它使用servlet将文件从服务器下载到用户的机器中。 Here is the code:这是代码:

String id_archivo = (request.getParameter("idArchivo") == null) ? "" : request.getParameter("idArchivo");
String nombre_archivo = (request.getParameter("nomArchivo") == null) ? "" : request.getParameter("nomArchivo");

//Para que se baje el archivo
response.setContentType("text/plain");
response.setHeader("Content-Disposition", "attachment;filename=\"" + nombre_archivo + "\"");

log.info("Buscando archivo nombre[" + nombre_archivo + "] id[" + id_archivo + "]");
byte[] archivo =getFile(id_archivo, nombre_archivo);
response.setContentLength(archivo.length);
ServletOutputStream sos = response.getOutputStream();

sos.write(archivo);
sos.flush();
sos.close();

The problem is that it doesn't download the file, it just shows it in the browser.问题是它不下载文件,它只是在浏览器中显示它。

You need to look into the Content-Disposition Header.您需要查看Content-Disposition标题。 It is explained here: http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html#sec19.5.1 - essentially it allows you to specify a "hint" to the browser to handle the file as a download.它在这里解释: http : //www.w3.org/Protocols/rfc2616/rfc2616-sec19.html#sec19.5.1 - 本质上它允许您指定浏览器的“提示”以将文件作为下载处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM