后台
@Controller
public class IndexController {
@Value("${my-config.file-path}")
private String myFilePath;
@RequestMapping("test")
public String test() {
return "index";
}
@RequestMapping("upload")
public String upload(@RequestParam("file") MultipartFile file, Model model, HttpServletRequest req) {
try {
String fileName = System.currentTimeMillis()+file.getOriginalFilename();
String destFileName=myFilePath+"uploaded"+ File.separator+fileName;
File destFile = new File(destFileName);
if (!destFile.getParentFile().exists()) {
destFile.getParentFile().mkdirs();
}
file.transferTo(destFile);
model.addAttribute("filename","uploaded/"+fileName);
} catch (FileNotFoundException e) {
e.printStackTrace();
return "上传失败," + e.getMessage();
} catch (IOException e) {
e.printStackTrace();
return "上传失败," + e.getMessage();
}
return "index";
}
@ResponseBody
@GetMapping("/download")
public String downloadImage(@RequestParam(value = "imageName",required = false) String filename, HttpServletRequest request, HttpServletResponse response) throws IOException {
String name = filename.split("/")[1];
File newfile = new File("D:/uploaded" + File.separator+name);
if (!newfile.exists()) {
throw new IOException(name + "文件不存在");
}
response.setContentType("application/force-download");
response.addHeader("Content-Disposition", "attachment;fileName=" + name);
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
OutputStream os = null;
try {
fis = new FileInputStream(newfile);
bis = new BufferedInputStream(fis);
os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
}catch (Exception e){
e.printStackTrace();
}finally {
os.close();
bis.close();
fis.close();
}
return "index";
}
}
配置文件
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
如下代码的意思是它会解析前端的图片路径并在“D://uploaded/”这个目录下去找相应的静态资源
@Configuration
public class MyWebAppConfigurer implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/uploaded/**").
addResourceLocations("file:/" + "D://uploaded/");
}
}
设置端口和文件的默认上传路径

前台
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.bootcss.com/jquery/3.5.0/jquery.js"></script>
</head>
<body>
<h3>文件上传</h3>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" >
<br>
<input type="submit" value="上传" >
</form>
[[${filename}]]
<br>
<img th:src="@{${filename}}" alt="图片" id="imgss">
<h3>文件下载</h3>
<form action="/download" method="get">
<input type="hidden" name="imageName" id="imageName" value=""/>
<input type = "submit" value="点击图片下载" >
</form>
<script th:inline="javascript">
$(document).ready(function(){
var message = [[${filename}]];
console.log(message);
$("#imgss").click(function(){
$("#imageName").val(message);
});
})
</script>
</body>
</html>
运行步骤:访问http://localhost:8899/test,点击上传文件后,浏览器上展示上传的图片,点击图片和下载按钮,选择下载路径,完成下载功能
SpringBoot 实现图片下载功能
本文介绍了如何使用SpringBoot来实现一个简单的图片下载功能。在后台配置中,通过设置静态资源路径和端口,使得系统能够根据前端提供的图片路径找到对应的文件。在前台,用户可以通过访问特定URL上传图片,并在页面上预览,点击图片可以触发下载,用户可以选择下载路径完成文件下载。
633

被折叠的 条评论
为什么被折叠?



