如何使用Servlet从服务器下载文件 [英] How to download a file from the server using Servlet

查看:191
本文介绍了如何使用Servlet从服务器下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是servlet技术的新手,我需要编写代码来从客户端的服务器下载文件。

I am new to servlet technology, i need to write code to download files from the server at client side.

我们可以使用servlet技术从服务器上下载文件吗?

Can we download files diectly from the server using servlet technology?

请提供宝贵的建议。

推荐答案

如果我理解正确,您可以通过response.sendRedirect()从HTTP servlet下载文件,以获取公共位置可用的文件。

If I understand you correctly, You can download the file from HTTP servlet via response.sendRedirect() for files available in public location.

否则,您需要使用响应输出流来绑定文件信息,以便它提示您下载文件:

Else you need to use the response output stream to bind the file information so that it will prompt you to download for a file:

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

我想你可以处理例外情况。

I gues you can handle the exceptions, of course.

这篇关于如何使用Servlet从服务器下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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