java的multfile_Java MultipartFile 使用记录

private void file(String path,MultipartFile file){

String separator = "/";

String originFileName = file.getOriginalFilename();//文件名称

String suffix = FileType.getSuffixByFilename(originFileName); //文件类型

originFileName = originFileName.substring(0, originFileName.length() - suffix.length()); //文件名称

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

String dateString = sdf.format(new Date());

StringBuffer filePath = new StringBuffer();

filePath.append(path).append(File.separator).append(dateString).append(File.separator);

File physicalPath = new File(filePath.toString());//创建文件存储位置

if (!physicalPath.exists()) physicalPath.mkdirs();

String newName = UUID.randomUUID().toString().replaceAll("-", "") + suffix; //随机生成文件名称

String physicalFileString = physicalPath.getAbsolutePath() + File.separator + newName; //文件存储位置

// 转存文件

File localFile = new File(physicalFileString); //创建文件对象

try {

file.transferTo(localFile); //文件写入新路径中

} catch (IOException e) {

e.printStackTrace();

}

StringBuffer fileUrl = new StringBuffer(dateString).append(separator).append(newName); //文件存储位置

}

存储多个文件使用 MultipartFile[] 遍历循环每个文件保存

Java中的MultipartFile是Spring框架中的一个接口,用于处理文件上传。下面是MultipartFile的详细使用方法: 1. 在前端表单中添加文件上传表单项 ```html <form method="post" enctype="multipart/form-data" action="/upload"> <input type="file" name="file"/> <input type="submit" value="上传"/> </form> ``` 2. 在后端Controller中接收文件上传请求 ```java @Controller public class UploadController { @PostMapping("/upload") public String upload(@RequestParam("file") MultipartFile file) { // 处理文件上传逻辑 return "redirect:/success"; } } ``` 3. 对MultipartFile进行处理 ```java @Controller public class UploadController { @PostMapping("/upload") public String upload(@RequestParam("file") MultipartFile file) throws IOException { // 获取文件名 String fileName = file.getOriginalFilename(); // 获取文件大小 long fileSize = file.getSize(); // 获取文件类型 String contentType = file.getContentType(); // 获取文件二进制内容 byte[] bytes = file.getBytes(); // ...处理文件上传逻辑 return "redirect:/success"; } } ``` 注意事项: 1. 表单中的enctype必须设置为multipart/form-data,否则无法上传文件。 2. 在Controller中接收MultipartFile时,需要使用@RequestParam注解,并指定表单项的name。 3. MultipartFile的getBytes方法会将整个文件读入内存,对于大文件上传需要进行优化。可以使用getInputStream方法将文件流读入,或者使用transferTo方法将文件写入磁盘。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值