项目静态资源文件夹目录文件夹下资源下载
资源目录如下
1.前端
<!-- 引入 layui.css -->
<link rel="stylesheet" href="//unpkg.com/layui@2.6.6/dist/css/layui.css">
<form class="layui-form" action="/downloadFile?token=234" >
<!-- 路径为静态资源位置,若不能访问,请参考博主静态资源访问文章-->
<img src="http://localhost:8080/static/upload/imgs/2021-05-15/52691946-7720-4055-a9fd-6bc04a15c4b4_图.png"/>
<input th:value="${token}" type="hidden" name="token"/>
<!-- value应该为文件名,由于项目是按日期生成文件夹的,所以我这传入部分相对路径做演示 -->
<button type="submit" name="fileName" value="imgs/2021-05-15/52691946-7720-4055-a9fd-6bc04a15c4b4_图.png"
class="layui-btn layui-btn-normal">图片下载</button>
</form>
2.业务端
@GetMapping("/downloadFile")
public void downloadFile(HttpServletResponse response,
@RequestParam("token") String token,
@RequestParam("fileName") String fileName)
throws FileNotFoundException, UnsupportedEncodingException {
//获取服务器文件
// 指定项目本地存储目录,不存在则需要提前创建项目根路径下的目录 SpringBoot static
String dirPath = "src/main/resources/static/upload/";
File filePath = new File(dirPath);
// 构建真实的文件路径, 图片的绝对路径
File tempFile = new File(filePath.getAbsolutePath() + File.separator + fileName);
InputStream ins = new FileInputStream(tempFile);
/* 设置文件ContentType类型,这样设置,会自动判断下载文件类型 */
response.setContentType("multipart/form-data");
/* 设置文件头:最后一个参数是设置下载文件名,文件名需要编码,不然中文不显示 */
String encodeFileName = new String(fileName.getBytes(),"ISO-8859-1");
response.setHeader("Content-Disposition", "attachment;filename="+encodeFileName);
try{
OutputStream os = response.getOutputStream();
byte[] b = new byte[1024];
int len;
while((len = ins.read(b)) > 0){
os.write(b,0,len);
}
os.flush();
os.close();
ins.close();
}catch (IOException ioe){
ioe.printStackTrace();
}
}
3.显示效果图,点击图片下载后会显示选择的路径,点击保存后就下载了
友情链接:Springboot下静态资源访问