Spring boot实现上传文件至本地或服务器

大家好 我是程序猿小张

图片文件上传是项目中必不可少的一个功能,上传的地址也当然是优先选择第三方的对象存储,例如七牛云、阿里云等等,但是当中的话只有七牛云是有一个免费额度的,其他都是要收钱的。所以就想着,哎,这个能不能上传到本地呢?答案是肯定可以的,只要你本地存储空间足够大,不多说上教程。

一、applicationp配置

#上传文件大小 默认是10MB
spring:
  servlet:
    multipart:
      max-file-size: 50MB
      max-request-size: 50MB
#本地上传地址,我这个是服务器地址,如是本地改成对应磁盘地址即可
file:
  upload-folder: /usr/local/blog/file/

二、controller层

@RequestMapping(value = "/upload",method = RequestMethod.POST)
    public ApiResult upload(MultipartFile multipartFile){
        return uploadUtil.upload(multipartFile);
    }

三、uploadUtil工具类

public ApiResult upload(MultipartFile file) {
	log.info("文件上传开始,时间 {}",DateUtils.getNowDate());
	if (file.getSize() > 1024 * 1024 * 10) {
  	     return ApiResult.fail("文件大小不能大于10M");
	}
	//获取文件后缀
	String suffix = file.getOriginalFilename().substring(file.getOriginalFil			 
        ename().lastIndexOf(".") + 1, file.getOriginalFilename().length());
        if (!"jpg,jpeg,gif,png".toUpperCase().contains(suffix.toUpperCase())) {
             return ApiResult.fail("请选择jpg,jpeg,gif,png格式的图片");
	}
 	String savePath = UPLOAD_FOLDER;
  	File savePathFile = new File(savePath);
 	if (!savePathFile.exists()) {
  	   //若不存在该目录,则创建目录
    	  savePathFile.mkdir();
 	}
 	 //通过UUID生成唯一文件名
  	String filename = UUIDUtil.getUuid() + "." + suffix;
  	try {
       	      //将文件保存指定目录
      	     file.transferTo(new File(savePath + filename));
   	} catch (Exception e) {
     	     e.printStackTrace();
     	     return ApiResult.fail("保存文件异常");
 	 }
	//返回文件名称
        return ApiResult.success(filename);
}

四、配置拦截器MyInterceptorConfig

@Configuration
public class MyInterceptorConfig extends WebMvcConfigurationSupport {

    @Value("${file.upload-folder}")
    private String UPLOAD_FOLDER;

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

五、放行img路径地址,如项目中使用到了shiro或Security则需放行路径,以下为Security

@Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(HttpMethod.GET,
                "/favicon.ico",
                "/img/**",
                "/**/*.png",
                "/**/*.ttf",
                "/*.html",
                "/**/*.css",
                "/**/*.js",
                "/index/**");
    }

至此整个上传就结束了,上传成功则可以使用地址如http://localhost:8800/img/xxx.jpg 进行访问

Bye

版权声明:本文为博主作者:程序猿小张丶原创文章,版权归属原作者,如果侵权,请联系我们删除!

原文链接:https://blog.csdn.net/weixin_45444807/article/details/131508964

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
xiaoxingxing的头像xiaoxingxing管理团队
上一篇 2024年4月16日
下一篇 2024年4月16日

相关推荐