Spring 上传文件

上传文件的功能几乎每位Java EE程序员都能遇到,使用Spring boot开发上传功能很简单。

第一步,做一个表单。这里采用模板thymeleaf。

上传Excle基础数据。文件最大200M。

上传文件
上传表单必须添加属性enctype=”multipart/form-data”。

上传类型为type=“file”

第二步,上传方法。

@PostMapping("/base/data/import")
public String upload(@RequestParam(“xfile”) MultipartFile xfile, RedirectAttributes redirectAttributes) {

String classpath = BaseDataController.class.getResource("/").getPath();
String save_path = classpath + “/upload”;
File file = new File(save_path);
if (!file.exists()) {
file.mkdirs();
}
String save_file = save_path + “/” + xfile.getOriginalFilename();
try {
xfile.transferTo(new File(save_file));
redirectAttributes.addFlashAttribute(“msg”, “已上传!”);
} catch (IllegalStateException | IOException e) {
log.error(“upload error:{}”, e);
redirectAttributes.addFlashAttribute(“msg”, “上传失败!”);
}
return “redirect:/base/data/import”;
}
请求参数类型为MultipartFile,用于获取上传文件。如:

@RequestParam(“xfile”) MultipartFile xfile

而方法transferTo()能将文件写入到磁盘。

void transferTo(File dest) throws IOException, IllegalStateException;

第三步,修改上传文件大小限制。修改配置文件application.properties,添加发下配置:

spring.servlet.multipart.max-file-size=200MB
spring.servlet.multipart.max-request-size=200MB
如果不修改这个配置,默认只能上传1M大小的文件。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值