SpringBoot文件上传--头像上传

目录

1.在配置文件中写好物理路径和访问路径

2.写配置文件

3.页面上传

4.控制层

5.效果

1.在配置文件中写好物理路径和访问路径

(自定义)file:
  uploadPath: D:/upload/img/  物理路径
  path: /file/**  访问路径

2.写配置文件

package com.example.uploaddemo.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
    @Value("${file.uploadPath}")
    String filelocation;
    @Value("${file.path}")
    String filepath;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //匹配到resourceHandler,将URL映射至location,也就是本地文件夹
        registry.addResourceHandler(filepath).addResourceLocations("file:" + filelocation);
        //这里最后一个file:不能不写
    }
}

控制层取到和配置文件中的物理路径和访问路径,并且写在方法中。

2424a42af3704c10a8687d09b11ba026.png

3.页面上传

在页面写好上传和保存,上传到对应的路径,对应好上传的数组名

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>上传图片</title>
</head>

<body>
<form th:action="@{/goUploadImg}" method="post" enctype="multipart/form-data">
    <input type="file" value="上传"  name="fileUpload">
    //将页面图片路径和前端存的路径绑定
    <img th:src="@{/file/{header}(header=${filename})}" height="200px" width="200px">

    <input type="submit" value="保存">
</form>

</body>
</html>

4.控制层

//    上传头像
    @RequestMapping("/goUploadImg")
    public String goUploadImg(MultipartFile[] fileUpload, Model model) {
        String allFile = "";
        //上传多个文件时,遍历存入
        for (MultipartFile file : fileUpload) {
            String filename = file.getOriginalFilename();
            String newFileName = "22610302150754.jpg";
            String uploadDir = "D:/upload/img/";//存入地址
            File fileDir = new File(uploadDir);
            if (!fileDir.exists()) //首先检查上传的文件夹是否存在
                fileDir.mkdirs(); //不存在就直接创建
            try {
                //上传指定的新的文件名的文件到指定的文件夹下
                allFile += filename + ",";
                file.transferTo(new File(uploadDir + newFileName));
                //路径存到前端页面上
                model.addAttribute("filename", newFileName);
                model.addAttribute("uploadStatus", allFile + "文件上传成功");
            } catch (IOException e) {
                model.addAttribute("uploadStatus", allFile + "文件上传失败");
                e.printStackTrace();
            }
        }
        return "uploadImg";
    }

    @RequestMapping("/img")
    public String goimg(){
        return "uploadImg";
    }
}

上传name和方法中数组名字相同

8b39d0cca7d64b19be57eb47e6ba90a3.png

5.效果

2ca8b4497cf8495085bb6a148e1e159e.png

c810e0aefb0846d2a158cd94e6445b9f.png

 

 

  • 5
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
要实现头像上传,可以结合Spring Boot后端框架,Vue前端框架以及Element UI组件库进行实现。 首先,在Vue前端页面中,可以使用Element UI中的Upload组件实现文件上传功能。可以在页面中定义一个Upload组件,设置action属性为上传接口的URL,设置headers属性为请求头部信息,设置on-success属性为上传成功后的回调函数。具体代码如下: ``` <template> <div> <el-upload class="avatar-uploader" action="/api/uploadAvatar" :headers="{ Authorization: 'Bearer ' + token }" :show-file-list="false" :on-success="handleSuccess"> <img v-if="imageUrl" :src="imageUrl" class="avatar"> <i v-else class="el-icon-plus avatar-uploader-icon"></i> </el-upload> </div> </template> <script> import { getToken } from '@/utils/auth' export default { data() { return { imageUrl: '', token: getToken() } }, methods: { handleSuccess(response) { this.imageUrl = response.data.url } } } </script> ``` 其中,token是用于认证的令牌,可以通过getToken函数获取。handleSuccess函数是上传成功后的回调函数,其中response.data.url表示上传成功后的图片URL。 然后,在Spring Boot后端接口中,可以使用Spring MVC的注解@RequestParam来接收上传的文件。具体代码如下: ``` @RestController @RequestMapping("/api") public class UploadController { @PostMapping("/uploadAvatar") public JsonResult uploadAvatar(@RequestParam("file") MultipartFile file) throws IOException { // 处理上传的文件 return JsonResult.ok("url", "http://www.example.com/avatar.jpg"); } } ``` 其中,@PostMapping注解表示接收POST请求,@RequestParam("file")注解表示接收名为file的文件参数。处理上传的文件后,可以返回一个JsonResult对象,其中包含上传成功后的图片URL。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

随便1007

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值