服务端文件下载功能及客户端使用apache.commons.httpclient下载

本文介绍了一个简单的Java Web应用程序中实现文件下载的方法。服务器端通过读取指定路径的文件并将其发送到客户端,客户端则利用HTTP GET请求从服务器下载文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


服务器端:

@RequestMapping("/jar-file")
	 public void downLoadFile(String downloadFilePath, HttpServletResponse response) throws IOException {
		 File file = new File(filePath + downloadFilePath);
		 if (!file.exists()) {
			 return;
		 }
		InputStream in = new FileInputStream(file);
		 byte[] body = new byte[in.available()];
		 in.read(body);
		 in.close();
		 OutputStream out = new BufferedOutputStream(response.getOutputStream());
		 response.setContentType("application/x-java-archive");
		 response.addHeader("Content-Disposition", "attachment;filename=mallwash_agent.jar");
		 out.write(body);
		 out.flush();
		 out.close();
	 }

客户端:

使用apache.commons.client

public static void main(String[] args) {
		try {
			CloseableHttpClient httpClient = HttpClients.createDefault();
			HttpGet request = new HttpGet(url);
			CloseableHttpResponse response = httpClient.execute(request);
			HttpEntity entity = response.getEntity();
			InputStream is = entity.getContent();
			File file = new File("/home/hao/开发/test.jar");
			if (!file.exists()) {
				file.createNewFile();
			}
			OutputStream os = new FileOutputStream(file);
			byte[] buffer = new byte[4096];
			int n = 0;
			while (-1 != (n = is.read(buffer))) {
				os.write(buffer, 0, n);
			}
//			IOUtils.copy(is, os);可使用apache工具
			os.flush();
			os.close();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

不能使用:

InputStream in = entity.getContent();
			 byte[] body = new byte[in.available()];
			 in.read(body);

估计是使用网络传输无法直接获取所有输入流内容



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值