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

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

问题描述

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

How should I implement simple file download servlet?

这个想法是,通过 GET 请求 index.jsp?filename=file.txt,用户可以下载例如.file.txt 来自文件 servlet,文件 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天全站免登陆