栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

简介

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

开发步骤

1、先贴图片上传工具类

package com.prereadweb.utils;
 
import java.io.File;
import java.io.FileOutputStream;
import java.util.UUID;
 

public class FileTool {
 
  
  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();
  }
 
  
  public static String renameToUUID(String fileName) {
    return UUID.randomUUID() + "." + fileName.substring(fileName.lastIndexOf(".") + 1);
  }
}

2、contoller层


  @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层


  @Override
  public Map fileUpload(MultipartFile file, Long userId) {
    Map 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 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;
 

@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;
 

@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报


 
   org.springframework.boot 
   spring-boot-configuration-processor 
   true 

8、postman测试接口

9、此时配置完成

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

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/137229.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号