前言
说到文件下载, 通常有两种情况,一种是我们作为服务器,提供资源给客户端下载,另一种是我们去网络资源下载我们想要的文件;先介绍服务器作为资源提供方,提供文件,图片等资源, 供客户端或者浏览器下载。 基础内容废话不多说, 直接上实现:
实现
1. 准备好一张图, 放在resources目录下, 我这里新建了个file目录, 123.png就是我们要提供给客户端下载的图片。

2. 控制层新建下载controller, 提供下载接口(真实开发下载实现最好放在service层):
@Controller
public class DownLoadController {
@GetMapping("/download")
@ResponseBody
public String downLoad (HttpServletRequest request, HttpServletResponse response) throws IOException {
// 1. 读取图片123.png
String realPath = "src/main/resources/file/123.png";
File file = new File(realPath);
String filename = file.getName();
// 2. 设置浏览器以下载方式打开, 此处不设置,会直接在浏览器预览图片
response.setHeader("content-disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
// 3. 读取文件,写到输出流
InputStream in = new FileInputStream(file);
byte[] buf = new byte[1024];
while (in.read(buf) > 0) {
response.getOutputStream().write(buf, 0, buf.length);
}
in.close();
return "下载完成";
}
}
3. 启动服务,打开浏览器访问测试:

4. 注意在response的header设置, 如果不想下载, 而是在浏览器直接预览方式打开, 则不用设置header。将下行删除即可
response.setHeader("content-disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
预览方式打开图片。
=============================分割线========================
从服务器下载文件
@Test
public void downloadNet() throws MalformedURLException {
String downLoadUrl = "https://t7.baidu.com/it/u=1595072465,3644073269&fm=193&f=GIF";
String fileName = "D:\\downLoad.png";
// 下载网络文件
int bytesum = 0;
int byteread = 0;
URL url = new URL(downLoadUrl);
try {
URLConnection conn = url.openConnection();
InputStream inStream = conn.getInputStream();
FileOutputStream fs = new FileOutputStream(fileName);
byte[] buffer = new byte[1204];
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread;
fs.write(buffer, 0, byteread);
}
inStream.close();
fs.close();
} catch (FileNotFoundException e) {
System.out.println("downloadNet FileNotFoundException exception " + e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.out.println("downloadNet IOException exception " + e);
}
}
本文介绍了如何在Java中使用SpringBoot实现文件下载。通过在控制器层创建下载接口,并设置响应头来触发浏览器的下载行为,详细展示了从服务器提供文件资源的步骤。
2109

被折叠的 条评论
为什么被折叠?



