springboot 下载文件

原创
2018/09/04 09:49
阅读数 655
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import Java.nio.file.Paths;

/**
 * 下载图片
 *
 * @author zcqshine
 */
@RestController
@RequestMapping("download")
public class DownloadController {

    private final ResourceLoader resourceLoader;

    @Value("${upload.file.path}")
    private String filePath;

    @Autowired
    public DownloadController(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    @GetMapping(value = "/{filename:.+}")
    public ResponseEntity<?> getFile(@PathVariable String filename) {
        try {
            String path = Paths.get(filePath, filename).toString();
            Resource resource = resourceLoader.getResource("file:" + path);
            return ResponseEntity.ok(resource);
        } catch (Exception e) {
            throw e;
        }
    }
}
展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
0 评论
1 收藏
0
分享
返回顶部
顶部