亲宝软件园·资讯

展开

SpringBoot图片上传和访问路径映射

人气:0

简介

做移动端对接,框架用的SpringBoot,接口RESTful,实现一个图片上传功能,图片上传是个经典的应用场景了,完成后,做个笔记记录一下,希望能帮到攻城狮们

开发步骤

1、先贴图片上传工具类

package com.prereadweb.utils;
 
import java.io.File;
import java.io.FileOutputStream;
import java.util.UUID;
 
/**
 * @Description: 文件工具类
 * @author: Yangxf
 * @date: 2019/4/17 16:06
 */
public class FileTool {
 
  /**
   * @Function: 图片上传
   * @author:  YangXueFeng
   * @Date:   2019/4/18 14:13
   */
  public static void uploadFiles(byte[] file, String filePath, String fileName) throws Exception {
    File targetFile = new File(filePath);
    if (!targetFile.exists()) {
      targetFile.mkdirs();
    }
    FileOutputStream out = new FileOutputStream(filePath + fileName);
    out.write(file);
    out.flush();
    out.close();
  }
 
  /**
   * @Function: 创建新的文件名
   * @author:  YangXueFeng
   * @Date:   2019/4/17 17:57
   */
  public static String renameToUUID(String fileName) {
    return UUID.randomUUID() + "." + fileName.substring(fileName.lastIndexOf(".") + 1);
  }
}

2、contoller层

/**
   * @Function: 用户图片上传
   * @author:  Yangxf
   * @Date:   2019/4/17 15:42
   */
  @PostMapping("/postfile")
  public Object fileUpload(@RequestParam(value = "userImg", required = false) MultipartFile file, @RequestParam(value = "userId", required = false) Long userId) {
    return personalService.fileUpload(file, userId);
  }

此处提一下@RequestParam注解

value:前台所传参数的名称

required:它有两个参数,true/false,默认是true,如果设置的是true的,客户端如果传值为空的话,访问此接口会报500异常,如果是false的话,客户端传值为空,会默认给参数赋值null

3、service层

/**
   * @Function: 用户头像上传
   * @author:  YangXf
   * @Date:   2019/4/17 15:41
   * @param:  file 图片
   * @param:  userId 用户ID
   * @return: map
   */
  @Override
  public Map<String, Object> fileUpload(MultipartFile file, Long userId) {
    Map<String, Object> map = new HashMap<>();
    if (Util.isEmpty(file)) {
      System.out.println("文件为空空");
      map.put("code", UserStatusEnum.EMPTY.intKey());
      map.put("msg", UserStatusEnum.EMPTY.value());
      return map;
    }
    UserEntity user = userMapper.fetchUser(userId);
    if(Util.isEmpty(user)){
      map.put("code", UserStatusEnum.USER_NOT_EXISTENCE.intKey());
      map.put("msg", UserStatusEnum.USER_NOT_EXISTENCE.value());
      return map;
    }
 
    String fileName = file.getOriginalFilename();
    fileName = FileTool.renameToUUID(fileName);
    try {
      FileTool.uploadFiles(file.getBytes(), uploadConfig.getUploadPath(), fileName);
    } catch (Exception e) {
    }
    if (Util.isEmpty(fileName)) {
      map.put("code", UserStatusEnum.USER_NOT_EXISTENCE.intKey());
      map.put("msg", UserStatusEnum.USER_NOT_EXISTENCE.value());
      return map;
    }
 
    Map<String, Object> returnMap = new HashMap<>();
    String url = "/static/" + fileName;
    updateUrl(userId, url);
    returnMap.put("imageUrl", url);
    map.put("code", UserStatusEnum.SUCCESS.intKey());
    map.put("msg", UserStatusEnum.SUCCESS.value());
    map.put("data", returnMap);
    return map;
  }

4、设置图片访问路径映射

preread: 
   #文件上传目录(注意Linux和Windows上的目录结构不同) 
   uploadPath: E:/image/

5、配置文件上传路径

package com.prereadweb.config.upload;
 
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
 
/**
 * @Description: 文件上传路径配置
 * @author: Yangxf
 * @date: 2019/4/17 17:50
 */
@Component
@ConfigurationProperties(prefix="preread")
public class PreReadUploadConfig {
 
  //上传路径
  private String uploadPath;
 
  public String getUploadPath() {
    return uploadPath;
  }
 
  public void setUploadPath(String uploadPath) {
    this.uploadPath = uploadPath;
  }
}

6、配置映射路径

package com.prereadweb.config.upload;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
 
/**
 * @Description: 自定义资源映射
 * <p>
 *   设置虚拟路径,访问绝对路径下资源
 * </p>
 * @author: Yangxf
 * @date: 2019/4/17 18:17
 */
@ComponentScan
@Configuration
public class WebConfigurer extends WebMvcConfigurerAdapter {
 
  @Autowired
  PreReadUploadConfig uploadConfig;
  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/static/**").addResourceLocations("file:///"+uploadConfig.getUploadPath());
  }
}

7、此处需要导入一个jar报

<!-- 配置 -->
 <dependency>
  <groupId> org.springframework.boot </groupId>
  <artifactId> spring-boot-configuration-processor </artifactId>
  <optional> true </optional>
</dependency>

8、postman测试接口

9、此时配置完成

图片的存储路径在:E:/image/

访问路径:http://127.0.0.1:8080/static/0fa7481d-4fec-42c3-a716-514feff73707.jpg

您可能感兴趣的文章:

加载全部内容

相关教程
猜你喜欢
用户评论