springboot实现简单的图片上传

springboot实现简单的图片上传

1. 创建配置类

/**
 * @author flame
 * @version 1.0.0
 * @date 2020/12/13 13:35
 */

@Data
@ConfigurationProperties("portal.file")
public class FileConfig {

    private List<String> imgList;
    private String imgServerAddress;//图片访问地址
    private String attachServerAddress;//附件访问地址
    private String imageContent;//图片目录
    private String attachContent;//附件目录
}

2. 配置文件中的自定义属性

portal:
  file:
    imgList:
      - .jpg
      - .png
    imgServerAddress: http://image.flame.com/images/ #开发环境
    attachServerAddress: http://image.flame.com/attachments/ #开发环境
    imageContent: D:/document/multi_blog/images #开发环境
    attachContent: D:/document/multi_blog/attachments #开发环境

3.创建Controller

/**
  * 图片上传
  *
  * @param file 图片
  * @return 视图对象
  */
 @PostMapping("/uploadImg")
 public Result uploadImg(@RequestBody MultipartFile file) {
     String originalFilename = file.getOriginalFilename();
     if (StringUtils.isBlank(originalFilename)) {
         return new Result(StatusCode.FILE_IS_NULL);
     }
     String extensionName = originalFilename.substring(originalFilename.lastIndexOf("."));
     if (!fileConfig.getImgList().contains(extensionName)) {
         return new Result(StatusCode.IMAGES_SORT_ERROR);
     }
     String newFileName = new Date().getTime() + extensionName;
     try {
         file.transferTo(new File(fileConfig.getImageContent(), newFileName));
     } catch (IOException e) {
         return new Result(StatusCode.FILE_UPLOAD_FAIL);
     }
     //返回url
     return new Result(StatusCode.OK, fileConfig.getImgServerAddress() + newFileName);
 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值