package com.itlike.web.file;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

@Controller
@RequestMapping("/file")
public class FileDownload {
    @GetMapping("/download/{id}")
    public ResponseEntity<byte[]> download() throws IOException {
        byte[] body = null;

        InputStream is = new FileInputStream("路径");
        body = new byte[is.available()];
        is.read(body);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", "attchement;filename=" + "1.png");
        HttpStatus statusCode = HttpStatus.OK;
        ResponseEntity<byte[]> entity = new ResponseEntity<>(body, headers, statusCode);
        return entity;
    }

}

以上只能支持小文件的下载,以下分享一个可以给大文件使用的文件下载工具类

public ResponseEntity<byte[]> download(String url,String filename) throws IOException{
        File file = new File(url);
        HttpHeaders headers=new HttpHeaders();
        //告诉浏览器以附件的形式打开,并且设置文件名的编码,防止乱码
        response.setHeader("Content-Disposition","attachment;filename="+URLEncoder.encode(filename,"UTF-8"));
        response.setContentType(filename);
        try(
                InputStream is = new FileInputStream(file);
                OutputStream os = response.getOutputStream();
        ){
            int read = 0;
            byte[] bytes = new byte[2048];
            while ((read = is.read(bytes)) != -1)
                os.write(bytes, 0, read);
        }
        System.out.println(filename);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers,HttpStatus.OK);
    }
Last modification:April 21, 2022
如果觉得我的文章对你有用,请随意赞赏