您现在的位置是:首页 > 后台技术 > JavaJava

Java下载静态资源(图文)

第十三双眼睛2024-07-19【Java】人已围观

简介有的时候,我们可能需要一些简单的下载功能,比如在项目里需要有导入功能,这时候需要一个下载模板的功能,我们就可以将预先编辑好的模板,放在项目中的静态资源目录下面,然后写一个接口,直接将预先放置好的模板返回,如果模板有变动,我们也不需要改代码,直接把模板进行替换即可。

首先,在resources目录下新建一个文件夹,用来存放静态文件,我这里叫template,然后把要下载的文件放进去

SpringBoot项目静态资源文件下载:代码如下:
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLEncoder;

/**
 * 文件下载
 *
 * @author zyb
 */
@RestController
@RequestMapping("excel")
public class ExcelController {

    @GetMapping("/download")
    public ResponseEntity<Resource> downloadFile() throws IOException, URISyntaxException {
        String filePath = "template/template.xlsx";
        URL resource1 = ExcelController.class.getClassLoader().getResource(filePath);
        Resource resource = new UrlResource(resource1.toURI());
        String charSet = "utf-8";
        if (resource.exists()) {
            String fileName = URLEncoder.encode(resource.getFilename(), charSet);
            return ResponseEntity.ok()
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"")
                .body(resource);
        } else {
            return ResponseEntity.notFound().build();
        }
    }
}
启动项目,打开浏览器,输入接口地址:http://localhost:9010/excel/download
可以看到文件已经下载成功了,同样的,打成jar包也是可以成功的

 

Tags:

很赞哦! ()

文章评论

    共有条评论来说两句吧...

    用户名:

    验证码:

站点信息

  • 网站名称:JavaStudy
  • 建站时间:2019-1-14
  • 网站程序:帝国CMS7.5
  • 文章统计246篇文章
  • 标签管理标签云
  • 统计数据百度统计
  • 微信公众号:扫描二维码,关注我们