您当前的位置: 首页 >  spring boot

ITKEY_

暂无认证

  • 0浏览

    0关注

    732博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Spring boot磁盘文件下载

ITKEY_ 发布时间:2021-04-08 15:07:01 ,浏览量:0

代码实现
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
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.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

/**
 * 文件下载Controller
 */

@Controller
@RequestMapping("/down/")
public class FileDownloadController {
    @GetMapping("hardDisk")
    public ResponseEntity hardDisk() {
        File hardDiskFile = new File("/Users/itkey/Desktop/temp.mp4");

        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(hardDiskFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        InputStreamResource inputStreamResource = new InputStreamResource(fileInputStream);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        httpHeaders.setContentDispositionFormData("attachment", hardDiskFile.getName());
        httpHeaders.setContentLength(hardDiskFile.length());
        return new ResponseEntity(inputStreamResource, httpHeaders, HttpStatus.CREATED);
    }
}

关注
打赏
1665243900
查看更多评论
立即登录/注册

微信扫码登录

0.0428s