java如何实现文件下载_java-实现一个简单的文件下载

假设您可以按以下方式访问servlet

http://localhost:8080/myapp/download?id=7

我需要创建一个servlet并将其注册到web.xml

web.xml

DownloadServlet

com.myapp.servlet.DownloadServlet

DownloadServlet

/download

DownloadServlet.java

public class DownloadServlet extends HttpServlet {

protected void doGet( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

String id = request.getParameter("id");

String fileName = "";

String fileType = "";

// Find this file id in database to get file name, and file type

// You must tell the browser the file type you are going to send

// for example application/pdf, text/plain, text/html, image/jpg

response.setContentType(fileType);

// Make sure to show the download dialog

response.setHeader("Content-disposition","attachment; filename=yourcustomfilename.pdf");

// Assume file name is retrieved from database

// For example D:\\file\\test.pdf

File my_file = new File(fileName);

// This should send the file to browser

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();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值