当前位置:   article > 正文

在springboot项目中编写超级简单的用户头像上传与回显的接口_springboot用户管理头像图片好几个

springboot用户管理头像图片好几个

废话不多说,直接上代码

@PostMapping("/upload")
    public ResponseResult upload(@RequestParam MultipartFile file){
        String path=System.getProperty("user.dir")+"/file/";
        String newFileName= UUID.randomUUID().toString().replaceAll("-","")+file.getOriginalFilename();
        File newFile=new File(path,newFileName);
        if (!newFile.getParentFile().exists()){
            newFile.getParentFile().mkdirs();
        }
        try {
            file.transferTo(newFile);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseResult(201,"上传失败");
        }
        String filePath="/upload/"+newFileName;
        return new ResponseResult(200,"保存成功",filePath);
    }

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

在启动类中

@SpringBootApplication
public class WebApplication {
    public static void main(String[] args) {
        SpringApplication.run(WebApplication.class,args);
    }
    
    @Bean
    public WebMvcConfigurer webMvcConfigurerUpload(){
        String uploadPath=System.getProperty("user.dir")+"/file/";
        return new WebMvcConfigurer() {
            @Override
            public void addResourceHandlers(ResourceHandlerRegistry registry) {
                registry.addResourceHandler("/upload/**")
                        .addResourceLocations("file:"+uploadPath+"/");
            }
        };
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/393434
推荐阅读
相关标签
  

闽ICP备14008679号