springboot 文件上传下载

配置文件配置文件存储路径

application:
  #版本
  version: 1.0.0
  #文件存储路径
  profile: /usr/local/tempfile/tempfile/

spring:
    #设置文件上限大小
  servlet:
    multipart: 
      enabled: true
      max-file-size: 200MB
      max-request-size: 200MB

注册读取配置文件类

@Component
@ConfigurationProperties(prefix = "application")
public class MyConfig {
	/**
     * 版本
     */
    private String version;
    private String profile;
    public String getVersion() {
		return version;
	}
	public void setVersion(String version) {
		this.version = version;
	}
	public String getProfile() {
		return profile;
	}
	public void setProfile(String profile) {
		this.profile = profile;
	}
}

关联访问资源与保存资源路径

@Configuration
public class ResourceConfig implements WebMvcConfigurer {
	
	@Autowired
	private MyConfig myconfig;
	//图片保存路径
    public static final String PIC_PATH = "/profile/";
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        /** 图片传路径 */
        registry.addResourceHandler("/profile/**").addResourceLocations("file:" + myconfig.getProfile());

    }
}

文件接收方法

MultipartFile file 为文件对象,变量名称必须和上传参数名一致
	@RequestMapping(value = "/fileUpload", method= RequestMethod.POST)
	public String fileUpload(VersionBean version, MultipartFile file,Model model) throws Exception {
		
		VersionBean versionBean = versionServer.getVersionBean(version.getPname());
		if(versionBean==null) {
			model.addAttribute("msg", "项目不存在");
			model.addAttribute("version", version);
			return "upload";
		}
		
		int compareVersion = VersionUtils.compareVersion(version.getCversion(), versionBean.getCversion());
		if(compareVersion<=0) {
			model.addAttribute("msg", "版本不能降序升级");
			model.addAttribute("version", version);
			return "upload";
		}
		
		String filenameString = null;
		if(file!=null&&file.getSize()>0) {
			filenameString = System.currentTimeMillis()+file.getOriginalFilename();
			String path= myconfig.getProfile()+filenameString;
//			System.out.println(path);
			File newFile=new File(path);
		    //通过CommonsMultipartFile的方法直接写文件(注意这个时候)
		    file.transferTo(newFile);
		    
		}
		if(filenameString!=null&&filenameString.length()>0) {
			version.setResoucepath(filenameString);
		}else {
			version.setResoucepath(null);
		}
		versionServer.update(version);
				
//		model.addAttribute("version", versionBean);
		model.addAttribute("msg", "更新成功");
		return String.format("redirect:/api/v1/version/%s", version.getPname());
	}

获取文件信息

地址为:服务地址/profile/文件名称 (例如:服务地址是:http://127.0.0.1:9000,下载资源的地址是:http://127.0.0.1:9000/profile/资源名称)
©️2020 CSDN 皮肤主题: 游动-白 设计师:上身试试 返回首页