SpringBoot中文件上传

一、在application.properties中配置路径映射:

配置上传文件路径

img.location = d:/mypicture

自定义的属性,指定了一个路径,注意要以/结尾

覆盖默认配置,所以需要将默认的也加上否则static、public等这些路径将不能被当作静态资源路径

spring.mvc.static-path-pattern=/**

在最末尾的file:${web.upload-path}中的file:表示是一个具体的硬盘路径,其他的使用classpath指的是系统环境变量

spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:${img.location}

二、编写文件上传配置类:
/**
* 文件上传配置类
*/
@Configuration
public class FileConfig {

@Value("${img.location}")
private String location;

@Bean
MultipartConfigElement multipartConfigElement() {
    MultipartConfigFactory factory = new MultipartConfigFactory();
    factory.setLocation(location);
    //文件最大
    factory.setMaxFileSize("5MB");
    // 设置总上传数据总大小
    factory.setMaxRequestSize("10MB");
    return factory.createMultipartConfig();
}

public String getLocation() {
    return location;
}

public void setLocation(String location) {
    this.location = location;
}

}

三、编写文件上传的工具类:
/**
* 文件上传工具类
*/
public class FileUtil {
/**
* 上传文件
* @param file 文件对应的byte数组流 使用file.getBytes()方法可以获取
* @param filePath 上传文件路径,不包含文件名
* @param fileName 上传文件名
* @throws Exception
*/
public static void uploadFile(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();
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值