spring boot中配置虚拟路径,用来映射显示图片

时间:2024-10-09 20:30:22

增加配置,继承 WebMvcConfigurerAdapter,如下:

  1. package .mogu_picture.config;
  2. import .factory.annotation.Value;
  3. import .Configuration;
  4. import ;
  5. import ;
  6. import .File;
  7. /**
  8. * @Description: 配置图片访问路径虚拟化
  9. * @Date: 2019/6/15
  10. * @Auther: wm yu
  11. */
  12. @Configuration
  13. public class AppConfig extends WebMvcConfigurerAdapter {
  14. @Value("${}")
  15. private String uploadUrl;
  16. @Value("${}")
  17. private String mappingUrl;
  18. /**
  19. * 得到的访问路径为当前项目端口路径 + /upload/image/
  20. * @param registry
  21. */
  22. @Override
  23. public void addResourceHandlers(ResourceHandlerRegistry registry) {
  24. /*
  25. * 说明:增加虚拟路径(经过本人测试:在此处配置的虚拟路径,用springboot内置的tomcat时有效,
  26. * 用外部的tomcat也有效;所以用到外部的tomcat时不需在tomcat/config下的相应文件配置虚拟路径了,阿里云linux也没问题)
  27. */
  28. (mappingUrl+"/**").addResourceLocations("file:"+ uploadUrl + File.separator);
  29. //阿里云(映射路径去除盘符)
  30. //("/ueditor/image/**").addResourceLocations("/upload/image/");
  31. super.addResourceHandlers(registry);
  32. }
  33. }

在项目中配置虚拟路径和真实路径(图片存储的路径)地址:

  1. #app
  2. server:
  3. port: 8602
  4. spring:
  5. profiles:
  6. active: local
  7. security:
  8. basic:
  9. enabled: false #spring boot中默认引入security的依赖就开启了security的功能,这里先禁用自动生效
  10. mogu:
  11. picture:
  12. upload: C:\mogu #定义文件上传的路径,真实地址
  13. mapping: /upload/image

上传图片的方法:

controller:

  1. @PostMapping("/uploadPic")
  2. @ApiOperation(value = "图片上传", notes = "图片上传")
  3. public Response<String> uploadPic(MultipartFile picFile){
  4. if(null == picFile){
  5. return Response.createError(MoguBlogContant.UPLOAD_PICTURE_EMPTY);
  6. }
  7. return fileService.uploadPic(picFile);
  8. }

 

service:

  1. @Override
  2. public Response<String> uploadPic(MultipartFile picFile) {
  3. if(null == picFile){
  4. return (MoguBlogContant.UPLOAD_PICTURE_EMPTY);
  5. }
  6. //上传路径
  7. String path = resourceMap.get(MoguBlogContant.PICTURE_PATH);
  8. //虚拟路径前缀
  9. String mappingPrefix = resourceMap.get(MoguBlogContant.PICTURE_MAPPING_PATH);
  10. //TODO 每次上传判断当天是否有文件夹,没有则创建一个,文件名称保持不变,使用redis记录文件,重复则不上传,直接返回虚拟路径
  11. //文件名
  12. String filename = ();
  13. File destFile = new File(path + File.separator + filename);
  14. try {
  15. (destFile);
  16. //拼接虚拟访问路径
  17. String url = mappingPrefix + File.separator + filename;
  18. return (MoguBlogContant.UPLOAD_PICTURE_SUCCESS,url);
  19. } catch (IOException e) {
  20. log.error("<uploadPic> 上传图片失败{}",filename,e);
  21. return (MoguBlogContant.UPLOAD_PICTURE_ERROR);
  22. }
  23. }

 

上传成功之后的访问路径为:  配置的项目基础访问路径+虚拟路径+图片名称,如:

http://localhost:8602/upload/image/u=3429654663,2972188411&fm=27&gp=

 

下面是文件上传的组件:(使用的是vue+element):

  1. <el-form-item label="用户头像">
  2. <div class="imgBody" v-show="showUpload1">
  3. <i class="el-icon-error inputClass" @click="deletePhoto" ></i>
  4. <img v-if="" v-bind:src="[0]" />
  5. </div>
  6. <el-upload
  7. class="upload-demo"
  8. drag
  9. :action = "pictureLoad()"
  10. name="picFile"
  11. v-show="showUpload2"
  12. :before-upload="beforeAvatarUpload"
  13. :on-success="uploadSuccess">
  14. <i class="el-icon-upload"></i>
  15. <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
  16. <div class="el-upload__tip" slot="tip">只能上传jpg/png文件,且不超过500kb</div>
  17. </el-upload>
  18. </el-form-item>

注意name="picFile"需要和后端的名称一致

还有注意需要后端处理跨域问题,如下代码:  在启动类中配置

  1. package com.wm.mogu_picture;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
  5. import org.springframework.boot.autoconfigure.velocity.VelocityAutoConfiguration;
  6. import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
  7. import org.springframework.context.annotation.Bean;
  8. import org.springframework.web.cors.CorsConfiguration;
  9. import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
  10. import org.springframework.web.filter.CorsFilter;
  11. import springfox.documentation.swagger2.annotations.EnableSwagger2;
  12. import tk.mybatis.spring.annotation.MapperScan;
  13. @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class,VelocityAutoConfiguration.class})
  14. @EnableSwagger2
  15. @EnableEurekaClient //注册到eureka,作为client
  16. @MapperScan(".mogu_picture.mapper")
  17. public class MoguPictureApplication {
  18. public static void main(String[] args) {
  19. SpringApplication.run(MoguPictureApplication.class, args);
  20. }
  21. /**
  22. * 跨域过滤器
  23. * @return
  24. */
  25. @Bean
  26. public CorsFilter corsFilter() {
  27. UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
  28. source.registerCorsConfiguration("/**", buildConfig()); // 4
  29. return new CorsFilter(source);
  30. }
  31. private CorsConfiguration buildConfig() {
  32. CorsConfiguration corsConfiguration = new CorsConfiguration();
  33. corsConfiguration.addAllowedOrigin("*");
  34. corsConfiguration.addAllowedHeader("*");
  35. corsConfiguration.addAllowedMethod("*");
  36. return corsConfiguration;
  37. }
  38. }

 

看下效果吧:

点击取消图片:

再次上传:

 

好了,只是贴出重要的代码,先记录吧