SpringBoot + Vue前后端分離圖片上傳到本地並前端訪問圖片


同理應該可用於其他文件

圖片上傳

application.yml

配置相關常量

prop:
  upload-folder: E:/test/
# 配置SpringMVC文件上傳限制,默認1M。注意MB要大寫,不然報錯。SpringBoot版本不同,配置項不同
spring:
  servlet:
    multipart:
      max-file-size: 50MB
      max-request-size: 50MB

Controller

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

@PostMapping("/upload")
public Result upload(@RequestParam(name = "file", required = false) MultipartFile file, HttpServletRequest request) {
    if (file == null) {
        return ResultUtil.error(0, "請選擇要上傳的圖片");
    }
    if (file.getSize() > 1024 * 1024 * 10) {
        return ResultUtil.error(0, "文件大小不能大於10M");
    }
    //獲取文件后綴
    String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1, file.getOriginalFilename().length());
    if (!"jpg,jpeg,gif,png".toUpperCase().contains(suffix.toUpperCase())) {
        return ResultUtil.error(0, "請選擇jpg,jpeg,gif,png格式的圖片");
    }
    String savePath = UPLOAD_FOLDER;
    File savePathFile = new File(savePath);
    if (!savePathFile.exists()) {
        //若不存在該目錄,則創建目錄
        savePathFile.mkdir();
    }
    //通過UUID生成唯一文件名
    String filename = UUID.randomUUID().toString().replaceAll("-","") + "." + suffix;
    try {
        //將文件保存指定目錄
        file.transferTo(new File(savePath + filename));
    } catch (Exception e) {
        e.printStackTrace();
        return ResultUtil.error(0, "保存文件異常");
    }
    //返回文件名稱
    return ResultUtil.success(ResultEnum.SUCCESS, filename, request);
}

前端訪問圖片

前端瀏覽器在http協議下因為安全原因無法直接訪問本地文件

后端攔截器中配置對應url訪問本地文件,若有相關攔截器則在攔截器中放行

@Configuration
public class MyInterceptorConfig extends WebMvcConfigurationSupport {

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

    @Autowired
    private JwtInterceptor jwtInterceptor;

    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(jwtInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns("/login")
                .excludePathPatterns("/img/**");
    }

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

前端直接通過/img/圖片名稱即可拿到


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM