SpringBoot中实现文件的下载--下载指定路径下的文件

代码参考如下:
一、接收页面下载的请求(后台Controller方法)

	/**
	 * 	文件下载
	 * @param response
	 * @param fId
	 * @return
	 */
	@RequestMapping("/down")
	@CrossOrigin(origins = "*", methods = {RequestMethod.GET, RequestMethod.POST})
    public String down(HttpServletResponse response,String fId) {
        try {
        	//根据文件id查询文件路径
        	FileInfo fileInfo=fileService.getFileVersion(fId);
			//根据文件路径下载文件信息
        	UploadUtil.down(response, fileInfo.getfPath());
			
			return "下载成功";
        } catch (IOException e) {
        	e.printStackTrace();
        }
        return "下载失败";
    }

二、代码中下载的工具类方法

/**
     * 下载
     * 由于HTTP头部的默认编码为ISO-8859-1而我们上传文件于下载文件过程中,提取到的文件名都要通过HTTP头部。
     *所以我们需要在上传的时候对提取到的文件名进行转码为UTF-8,然后在下载时我们也要进行反向转码为ISO-8859-1.
     * @param res
     * @param pathAddress
     */
    public static void down(HttpServletResponse res,String pathAddress) throws UnsupportedEncodingException {
        File file=new File(pathAddress);
        String fileName = file.getName();
        
        res.setHeader("content-type", "application/octet-stream");
        res.setContentType("application/octet-stream");
        res.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"),"iso-8859-1"));
        
        byte[] buff = new byte[1024];
        FileInputStream bis = null;
        OutputStream os = null;
        try {
            os = res.getOutputStream();
            bis = new FileInputStream(file);
            int readTmp = 0;
			while ((readTmp = bis.read(buff)) != -1) {
			//并不是每次都能读到1024个字节,所有用readTmp作为每次读取数据	的长度,否则会出现文件损坏的错误
				os.write(buff, 0, readTmp);
				
			}
			
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) try {
                bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println("success");
    }
在 Spring Boot ,可以通过设置响应头信息来实现文件下载。具体步骤如下: 1. 在控制器编写一个下载文件的方法,例如: ```java @GetMapping("/download") public ResponseEntity<Resource> downloadFile(@RequestParam("filename") String filename) { // 获取文件资源 Resource resource = new FileSystemResource("/path/to/files/" + filename); // 设置响应头 HttpHeaders headers = new HttpHeaders(); headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\""); // 返回响应实体 return ResponseEntity.ok() .headers(headers) .contentLength(resource.getFile().length()) .contentType(MediaType.APPLICATION_OCTET_STREAM) .body(resource); } ``` 2. 在请求时,通过访问 `/download?filename=xxx` 的方式来触发文件下载。其,`filename` 参数为要下载文件名。 在上述代码,`Resource` 对象用于获取文件资源,并且 `FileSystemResource` 是其一种实现方式。`HttpHeaders` 对象用于设置响应头信息,其 `CONTENT_DISPOSITION` 用于指定文件下载方式,`attachment` 表示以附件形式进行下载。`ResponseEntity` 对象用于构建响应实体,其 `ok()` 方法表示请求成功,`.headers()` 方法用于设置响应头信息,`.contentLength()` 方法用于设置响应体长度,`.contentType()` 方法用于设置响应体类型,`.body()` 方法用于设置响应体内容。最终,返回 `ResponseEntity` 对象即可实现文件下载
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Monika、

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值