下载附件,返回文件流

package com.example.common.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.http.HttpStatus;
import com.example.common.entity.SysFile;
import com.example.common.service.SysFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.nio.charset.StandardCharsets;

@Validated
@Api(tags = "文件")
@RestController
@RequiredArgsConstructor
@RequestMapping("/file")
public class SysFileController {

    private final SysFileService fileService;

    @Value("${file-path}")
    private String basePath;

    /**
     * 文件下载
     * @param id
     * @param response
     */
    @GetMapping("/{id}")
    @ApiOperation("获取文件")
    public void get(@PathVariable String id, HttpServletResponse response) {
        SysFile file = fileService.getById(id);
        if (file != null) {
            //文件名乱码处理
            URLUtil.encode(file.getName(), StandardCharsets.UTF_8);
            //告知浏览器文件的类型(响应体)
            response.setContentType(file.getContentType());
            response.setContentLength(file.getSize().intValue());
            //告知浏览器以附件的方式提供下载功能, 而不是解析
            response.setHeader("Content-Disposition", "attachment;fileName=" + URLUtil.encode(file.getName(), StandardCharsets.UTF_8));
            ServletUtil.write(response, FileUtil.getInputStream(StrUtil.addSuffixIfNot(basePath, File.separator) + file.getPath()));
        } else {
            response.setStatus(HttpStatus.HTTP_NOT_FOUND);
        }
    }
 
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值