springboot 上传图片

1.目录结构 如图:

            

2.后端代码:

@RequestMapping("upload")
@RestController
public class UploadController {

    @Autowired
    private UploadService uploadService;
    /**
     * 上传图片
     */
    @PostMapping("image")
    public BaseResult uploadImage(@RequestParam("file") MultipartFile file) throws LyException {
        return ResultUtil.success(uploadService.uploadImage(file)) ;
    }
}

 

@Service
@Slf4j
public class UploadService {

    private static final List<String> ALLOW_TYPE = Arrays.asList("image/jpg","image/png","image/bmp");

    public String uploadImage(MultipartFile file) throws LyException {
        String fileName = file.getOriginalFilename();
        fileName = UUID.randomUUID().toString().replace("-", "")
                + fileName.substring(fileName.lastIndexOf("."));
        File dest = new File("F:\\upload" ,fileName);
        try {
            //校验文件类型
            String contentType = file.getContentType();
            if(ALLOW_TYPE.contains(contentType)){
                throw new LyException(ExceptionEnum.IMAGE_TYPE_ERROR);
            }

            //校验文件内容
            BufferedImage read = ImageIO.read(file.getInputStream());
            if(read == null){
                throw  new LyException(ExceptionEnum.PRICE_CANNOT_BE_NULL.IMAGE_TYPE_ERROR);
            }
            file.transferTo(dest);
            return  "http://localhost:8080/queryIma/"+fileName;
            //啰嗦一句 ,如果是springcloud 集群 应该返回集群路径
            //如:return "http://api.taobao.com/api/upload/queryIma/"+fileName;
        } catch (IOException e) {
             //记录日志
            log.error("上传文件失败",e );
            throw new LyException(ExceptionEnum.FILE_UPLOAD_ERROR);
        }
    }
}

 

@Configuration
public class MyWebMvcConfigurer implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        registry.addResourceHandler( "/queryIma/**")
                .addResourceLocations("file:"+ "F:/upload/"); //本地保存路径
        //registry.addResourceHandler( "/upload/queryIma/**") 
               .addResourceLocations("file:"+ "F:/upload/"); //对应上面集群路径,去掉/api
    }
}

 

 

这篇文章 更好:https://www.cnblogs.com/hhhshct/p/9121158.html

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值