实现一个简单的文件下载servlet [英] Implementing a simple file download servlet

查看:149
本文介绍了实现一个简单的文件下载servlet的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何实现简单的文件下载servlet?

How should I implement simple file download servlet?

想法是使用GET请求 index.jsp?filename = file.txt ,用户可以下载例如。来自文件servlet的 file.txt ,文件servlet会将该文件上传到用户。

The idea is that with the GET request index.jsp?filename=file.txt, the user can download for example. file.txt from the file servlet and the file servlet would upload that file to user.

我可以获取文件,但是如何实现文件下载?

I am able to get the file, but how can I implement file download?

推荐答案

这取决于。如果所述文件可以通过HTTP服务器或servlet容器公开获得,您可以通过 response.sendRedirect()重定向到

That depends. If said file is publicly available via your HTTP server or servlet container you can simply redirect to via response.sendRedirect().

如果不是,您需要手动将其复制到响应输出流:

If it's not, you'll need to manually copy it to response output stream:

OutputStream out = response.getOutputStream();
FileInputStream in = new FileInputStream(my_file);
byte[] buffer = new byte[4096];
int length;
while ((length = in.read(buffer)) > 0){
    out.write(buffer, 0, length);
}
in.close();
out.flush();

当然,您需要处理适当的异常。

You'll need to handle the appropriate exceptions, of course.

这篇关于实现一个简单的文件下载servlet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆