增加配置,继承 WebMvcConfigurerAdapter,如下:
package com.wm.mogu_picture.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.io.File;
/**
* @Description: 配置图片访问路径虚拟化
* @Date: 2019/6/15
* @Auther: wm yu
*/
@Configuration
public class AppConfig extends WebMvcConfigurerAdapter {
@Value("${mogu.picture.upload}")
private String uploadUrl;
@Value("${mogu.picture.mapping}")
private String mappingUrl;
/**
* 得到的访问路径为当前项目端口路径 + /upload/image/
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
/*
* 说明:增加虚拟路径(经过本人测试:在此处配置的虚拟路径,用springboot内置的tomcat时有效,
* 用外部的tomcat也有效;所以用到外部的tomcat时不需在tomcat/config下的相应文件配置虚拟路径了,阿里云linux也没问题)
*/
registry.addResourceHandler(mappingUrl+"/**").addResourceLocations("file:"+ uploadUrl + File.separator);
//阿里云(映射路径去除盘符)
//registry.addResourceHandler("/ueditor/image/**").addResourceLocations("/upload/image/");
super.addResourceHandlers(registry);
}
}
在项目中配置虚拟路径和真实路径(图片存储的路径)地址:
#app
server:
port: 8602
spring:
profiles:
active: local
security:
basic:
enabled: false #spring boot中默认引入security的依赖就开启了security的功能,这里先禁用自动生效
mogu:
picture:
upload: C:\mogu #定义文件上传的路径,真实地址
mapping: /upload/image
上传图片的方法:
controller:
@PostMapping("/uploadPic")
@ApiOperation(value = "图片上传", notes = "图片上传")
public Response uploadPic(MultipartFile picFile){
if(null == picFile){
return Response.createError(MoguBlogContant.UPLOAD_PICTURE_EMPTY);
}
return fileService.uploadPic(picFile);
}
service:
@Override
public Response uploadPic(MultipartFile picFile) {
if(null == picFile){
return Response.createError(MoguBlogContant.UPLOAD_PICTURE_EMPTY);
}
//上传路径
String path = resourceMap.get(MoguBlogContant.PICTURE_PATH);
//虚拟路径前缀
String mappingPrefix = resourceMap.get(MoguBlogContant.PICTURE_MAPPING_PATH);
//TODO 每次上传判断当天是否有文件夹,没有则创建一个,文件名称保持不变,使用redis记录文件,重复则不上传,直接返回虚拟路径
//文件名
String filename = picFile.getOriginalFilename();
File destFile = new File(path + File.separator + filename);
try {
picFile.transferTo(destFile);
//拼接虚拟访问路径
String url = mappingPrefix + File.separator + filename;
return Response.createSuccess(MoguBlogContant.UPLOAD_PICTURE_SUCCESS,url);
} catch (IOException e) {
log.error(" 上传图片失败{}",filename,e);
return Response.createError(MoguBlogContant.UPLOAD_PICTURE_ERROR);
}
}
上传成功之后的访问路径为: 配置的项目基础访问路径+虚拟路径+图片名称,如:
http://localhost:8602/upload/image/u=3429654663,2972188411&fm=27&gp=0.jpg
下面是文件上传的组件:(使用的是vue+element):
将文件拖到此处,或点击上传
只能上传jpg/png文件,且不超过500kb
注意name="picFile"需要和后端的名称一致
还有注意需要后端处理跨域问题,如下代码: 在启动类中配置
package com.wm.mogu_picture;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.velocity.VelocityAutoConfiguration;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import tk.mybatis.spring.annotation.MapperScan;
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class,VelocityAutoConfiguration.class})
@EnableSwagger2
@EnableEurekaClient //注册到eureka,作为client
@MapperScan("com.wm.mogu_picture.mapper")
public class MoguPictureApplication {
public static void main(String[] args) {
SpringApplication.run(MoguPictureApplication.class, args);
}
/**
* 跨域过滤器
* @return
*/
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig()); // 4
return new CorsFilter(source);
}
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
return corsConfiguration;
}
}
看下效果吧:
点击取消图片:
再次上传:
好了,只是贴出重要的代码,先记录吧