文件上传自定义上传路径

 ̄綄美尐妖づ 提交于 2019-12-05 04:07:34

文件上传自定义上传路径,并且根据返回的Url可以进行访问

配置文件  .yml

#文件上传路径
file:
  #虚拟路径,对外展示
  staticAccessPath: /file/**
  #本地测试真实路径,可以改为服务器tomcat中路径
  fileupload:  F:/fileupload/

WebConfig类

/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有,侵权必究!
 */

package io.renren.common.config;

import lombok.Data;
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.WebMvcConfigurer;


 
/**
 * @author: HYJ
 * @program: ivvdata-security
 * @description: 文件路径以及WebMvc配置
 * @create: 2019-11-15 10:13
 */
@Data
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Value("${file.fileupload}")
    private String fileupload;

    @Value("${file.staticAccessPath}")
    private String staticAccessPath;


    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler(staticAccessPath).addResourceLocations("file:" + fileupload);

    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/statics/**").addResourceLocations("classpath:/statics/");
    }

}

Controller层

@PostMapping("/upload")
public R upload(@RequestParam("photo")MultipartFile photo) {// 定义上传文件存放的路径
         String path = configProperties.getFileupload() + "uploadPhotos/";
         System.out.println(path);
         // 定义文件在上传路径中的文件夹名称
         File folder = new File(path);
         // 检测folder是否是文件夹,不是就创建
         if (!folder.isDirectory()) {
             folder.mkdirs();
          }
          try {
            // 获取文件的原始名称
             String photoName = idCardFront.getOriginalFilename();            
             // 文件保存操作
             photo.transferTo(new File(folder, photoName));             
             // 访问的url
             String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
             String photoPath = basePath + configProperties.getStaticAccessPath().substring(0, configProperties.getStaticAccessPath().lastIndexOf("/") + 1) + "uploadPhotos/" + photoName ;       
             System.out.println(basePath);
             System.out.println(photoPath );
             return R.ok();
          } catch (IOException e) {
             return R.error();
         }
}        

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!