Springboot上传图片、头像

controller层 图片上传

 
 //   图片上传(复制代码后如果是idea,按alt+enter导入相应的包)
    @ApiOperation(value = "上传头像")
    @PostMapping("/upload/image")
    public ApiRestResponse uploadImg(HttpServletRequest httpServletRequest, @RequestParam("file")MultipartFile file){
        if (file.isEmpty()) {
            System.out.println("文件为空");
        }
        String fileName = file.getOriginalFilename();  // 文件名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
        fileName = UUID.randomUUID() + suffixName; // 新文件名
        File dest = new File(Constant.Upload_File_Dir+fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            return ApiRestResponse.success(getHost(new URI(httpServletRequest.getRequestURL()+""))+"/imgs/"+fileName);
        } catch (URISyntaxException e) {
            return ApiRestResponse.error(ImoocMallExceptionEnum.UPLOAD_IMG);
        }
    }
    //    获取IP、端口号
    private URI getHost(URI uri){
        URI effectiveURI;
        try {
            effectiveURI = new URI(uri.getScheme(),uri.getUserInfo(),uri.getHost(),uri.getPort(),null,null,null);
        } catch (URISyntaxException e) {
            effectiveURI=null;
        }
        return effectiveURI;
    }

Constant公共类

//upload.file.dir是存放图片的位置,在application.properties中配置,如下:
//upload.file.dir=F:/QualitySupervision/demo_project/src/main/resources/static/imgs/
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component //遗漏

public class Constant {
    public static final String Imooc_Mall_User="Imooc_Mall_User";
    //    图片地址
    public static  String Upload_File_Dir;
    @Value("${upload.file.dir}")

    public void setUploadFileDir(String uploadFileDir){
        Upload_File_Dir=uploadFileDir;
    }
}

在这里插入图片描述

ImoocMallExceptionEnum是定义的枚举类

package com.lbcc.exception;

/**
 * 异常枚举
 */
public enum ImoocMallExceptionEnum {
    INSERT_SUCCESS(10001,"插入成功"),
    REQUEST_ERROR(10020,"参数错误"),
    INSERT_FAIL(10002,"插入失败"),
    UPLOAD_IMG(10003,"上传图片失败"),
    SYSTEM_ERROR(20000,"系统异常");
    private Integer code;
    private String message;
    ImoocMallExceptionEnum(Integer code, String msg) {
        this.code = code;
        this.message = msg;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMsg() {
        return message;
    }

    public void setMsg(String msg) {
        this.message = msg;
    }
}
application.properties配置存储图片的地址

在这里插入图片描述
在这里插入图片描述

最后一步你会发现上传成功了,但是返回的地址在浏览器访问显示404,用以下方法解决(在config中新建一个配置文件UploadConfig ,代码如下):
package com.example.config;

import com.example.common.Constant;
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 UploadConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/imgs/**").addResourceLocations("file:"+Constant.Upload_File_Dir);
    }

}

在这里插入图片描述

这样就完美的解决了!!
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
在Spring Boot中上传图片头像可以使用Spring MVC的MultipartFile接口进行实现,具体步骤如下: 1. 在前端页面中添加一个文件上传的input框,并设置name属性为file: ``` <form method="POST" enctype="multipart/form-data" action="/upload"> <input type="file" name="file"> <button type="submit">上传</button> </form> ``` 2. 在后端Controller中添加一个POST请求处理方法,该方法的参数为MultipartFile类型的file参数: ``` @PostMapping("/upload") public String handleFileUpload(@RequestParam("file") MultipartFile file) { // 处理上传文件 return "redirect:/success"; } ``` 3. 在处理方法中,可以使用MultipartFile的transferTo()方法将文件保存到服务器本地: ``` @PostMapping("/upload") public String handleFileUpload(@RequestParam("file") MultipartFile file) { if (file.isEmpty()) { return "上传失败,请选择文件"; } try { // 获取文件名 String fileName = file.getOriginalFilename(); // 获取文件后缀 String suffixName = fileName.substring(fileName.lastIndexOf(".")); // 文件上传后的路径 String filePath = "/path/to/upload/directory/"; // 新文件名 fileName = UUID.randomUUID() + suffixName; // 创建文件目录 File dest = new File(filePath + fileName); // 保存文件 file.transferTo(dest); return "redirect:/success"; } catch (IOException e) { e.printStackTrace(); } return "上传失败!"; } ``` 4. 最后,在处理完成后,可以将用户头像的访问路径保存到数据库中,或者直接将访问路径返回给前端页面进行显示。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

herry-弟弟

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

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

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

打赏作者

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

抵扣说明:

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

余额充值