springboot 图片上传

/**
 * 系统设置
 */
@Slf4j
@RestController
@RequestMapping("/sysSite")
@Api(tags = "系统设置页面")
public class SysSiteController {

 @Value("${SavePath.ProfilePhoto}")
    private String profilePhotoSavePath;   //图标图片存储路径
    @Value("${SavePath.ProfilePhotoMapper}")
    private String profilePhotoMapperPath;   //图标映射路径
    @Value("${SavePath.url}")
    private String url;
    @Value("${server.port}")
    private String port;

  @ApiOperation(value = "车型配置页面--图片上传", notes = "保存信息")
        @PostMapping("/imageUpload")
        public ReturnObject imageUpload (MultipartFile file){
            if (file == null)
                throw new ErrorInfoException("图片不能为空");

            //得到上传文件的文件名
            String fileName = file.getOriginalFilename();
            //以传入的字符串开头,到该字符串的结尾,前开后闭
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            long size = file.getSize();
            double mul = NumberUtil.div(size, (1024 * 1024), 2);
// ErrorInfoException 是自定义得异常
            if (mul > 2)
                throw new ErrorInfoException("图片大小不能大于2M");
            if (!isImage(suffixName))
                throw new ErrorInfoException("不是图片格式");
                // 这里可以用uuid等 拼接新图片名
            String newFileName = SequenceUtil.getSequence("") + suffixName;
            // 创建路径
            String destFileName = this.profilePhotoSavePath + File.separator + newFileName;
            File destFile = new File(destFileName);
            if (!destFile.getParentFile().exists())
                destFile.getParentFile().mkdirs();
            try {
                //将图片保存到文件夹里
                file.transferTo(new File(profilePhotoSavePath + newFileName));
            } catch (IOException e) {
                e.printStackTrace();
                throw new ErrorInfoException("图片上传错误");
            }
            // 服务器主机
            String endPoint = this.url;
            String port = this.port;
            String imageUrl = new StringBuilder(endPoint)
                    .append(":")
                    .append(port)
                    .append(profilePhotoMapperPath)
                    .append(newFileName)
                    .toString();
// 返回拼接好的上传路径 给前端 ,前端可以直接展示 或者 如有其他参数需要和图片保存的 也可带着路径
// 和其他参数 请求另一个接口 保存
            return ReturnObject.success(imageUrl);
        }

    /**
     * 传进 .jpg  类似的格式 判断是否时图片格式
     * @param suffixName 图片格式后缀
     * @return
     */
    public static boolean isImage(String suffixName) {
        List<String> strings = Arrays.asList(".webp", ".png", ".jpg", ".jif", ".jpeg");
        if (strings.contains(suffixName))
            return true;
        return false;
    }



}

启动类 设置图片大小  spring boot 有默认的 太小了, 我需要判断 才设置

@Configuration
@EnableScheduling
@EnableWebSocket
@SpringBootApplication
public class DataAcquisitionApplication {

    @Autowired
    private RestTemplateBuilder builder;

    @Bean
    public RestTemplate restTemplate() {
        return builder.build();
    }


    /**
     * 配置上传文件大小的配置
     *
     * @return
     */
    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        //  单个数据大小
        factory.setMaxFileSize("102400KB");
        /// 总上传数据大小
        factory.setMaxRequestSize("102400KB");
        return factory.createMultipartConfig();
    }

    public static void main(String[] args) {
        Long startTime = System.currentTimeMillis();
        SpringApplication.run(DataAcquisitionApplication.class, args);
    }
}

appli'cation.yml 设置上传文件大小

spring:
    servlet:
    multipart:
      max-file-size: 100M #单个文件大小
      max-request-size: 100M # 总文件大小(允许存储文件的文件夹大小)

# 图片上传地址
SavePath:
#  ProfilePhoto: '/mnt/image/'  #图标存储路径
  ProfilePhoto: 'D:\资料\'  #图标存储路径
  ProfilePhotoMapper: '/profilePhoto/'  #图标的映射路径
  url: 'http://00.00.00.0'   #后端地址

server:
  port: 808

图片映射地址配置




import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.validation.MessageCodesResolver;
import org.springframework.validation.Validator;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.config.annotation.*;

import java.util.List;

@Configuration
public  class SpringbootConfigure implements WebMvcConfigurer {
    //@Value可以将配置文件的内容自动注入到属性内
    @Value("${SavePath.ProfilePhoto}")
    private String ProfilePhotoPath;   //图标物理存储路径
    @Value("${SavePath.ProfilePhotoMapper}")
    private String ProfilePhotoMapperPath;   //图标映射路径

// 其他的 @Override 重写方法 这里用不到 忽略不写了 

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry){
        registry.addResourceHandler(ProfilePhotoMapperPath+"**").addResourceLocations("file:"+ProfilePhotoPath)
        ;
    }
}

这样 在图片上传上去 返回的路径 就可以用拼接的路径在浏览器直接打开看了

如: http://00.00.00.0:808/profilePhoto/16581321838830000.jif

http://00.00.00.0:808 为 后端的项目路径

profilePhoto 为映射的路径

16581321838830000.jif 是图片名

当前文章 个人只当是笔记记录 有不妥之处  望指正  谢谢

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值