springboot实现简单的文件上传与回显

前端页面
input的file类型可以将上传文件的绝对路径返回给后台。

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <script src="http://libs.baidu.com/bootstrap/3.0.3/js/bootstrap.min.js"></script>
    <link href="http://libs.baidu.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet">
    <title>Title</title>
</head>
<body>
<div class="container">
    <body>
    <div class="col-md-12">
        <form action="/upload/upload" method="post" enctype="multipart/form-data">
            <input type="file" name="file" accept="image/*">
            <br>
            <input type="submit" value="上传" class="btn btn-success">
        </form>
        [[${filename}]]
        <br>
        <img th:src="@{${filename}}" alt="图片">

    </div>
    </body>
</div>
</body>
</html>

application.properties配置文件

file.upload.path=D://images/
file.upload.path.relative=/images/**
spring.thymeleaf.cache=false

MyWebAppConfigurer配置类
主要配置资源映射,在服务器输入路径时寻找对应映射文件。否则直接放在tomcat服务器中,由于springboot每次启动都会重启一个新的tomcat服务器,文件会丢失,所以放在其他路径,而通过资源映射则可以访问tomcat服务器以外的文件。

/**
 * 资源映射路径
 */
@Configuration
public class MyWebAppConfigurer implements WebMvcConfigurer {
    /**上传地址*/
    @Value("${file.upload.path}")
    private String filePath;
    /**显示相对地址*/
    @Value("${file.upload.path.relative}")
    private String fileRelativePath;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler(fileRelativePath).
                addResourceLocations("file:/" + filePath);
    }
}

Controller,
这里注意一个问题,getOriginalFilename在ie浏览器中会获取全部路径名从而造成io异常,其他浏览器正常,解决的话加个浏览器判断就好。

@Controller
@RequestMapping("upload")
public class UploadController {
    /**上传地址*/
    @Value("${file.upload.path}")
    private String filePath;


    @GetMapping("toUpload")
    public String toUpload(){
        return "upload";
    }

    @RequestMapping("upload")
    public String upload(@RequestParam("file") MultipartFile file, Model model) {
        // 获取上传文件名
        String filename = file.getOriginalFilename();
        // 定义上传文件保存路径
        String path = filePath+"Photo/";
        // 新建文件
        File filepath = new File(path, filename);
        // 判断路径是否存在,如果不存在就创建一个
        if (!filepath.getParentFile().exists()) {
            filepath.getParentFile().mkdirs();
        }
        try {
            // 写入文件
            file.transferTo(new File(path + File.separator + filename));
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 将src路径发送至html页面
        model.addAttribute("filename", "/images/Photo/"+filename);
        return "upload";
    }
}

测试
在这里插入图片描述

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值