使用springboot简单实现下载图片的功能

本文介绍了如何使用SpringBoot来实现一个简单的图片下载功能。在后台配置中,通过设置静态资源路径和端口,使得系统能够根据前端提供的图片路径找到对应的文件。在前台,用户可以通过访问特定URL上传图片,并在页面上预览,点击图片可以触发下载,用户可以选择下载路径完成文件下载。

使用springboot简单实现下载图片的功能

后台

@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,点击上传文件后,浏览器上展示上传的图片,点击图片和下载按钮,选择下载路径,完成下载功能

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值