MultipartFile 如何转换成File
时间: 2023-11-20 19:58:13 浏览: 159
MultipartFile可以通过以下三种方式转换成File:
1.使用transferTo()方法将MultipartFile转换成File:
```java
public File transferToFile(MultipartFile multipartFile) {
File file = null;
try {
String originalFilename = multipartFile.getOriginalFilename();
String[] filename = originalFilename.split("\\.");
file=File.createTempFile(filename[0], filename[1]);
multipartFile.transferTo(file);
file.deleteOnExit();
} catch (IOException e) {
e.printStackTrace();
}
return file;
}
```
2.使用FileUtils.copyInputStreamToFile()方法将MultipartFile转换成File:
```java
File file = new File(path);
FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), file);
```
3.使用NIO将MultipartFile转换成File:
```java
public File transferToFile(MultipartFile multipartFile) {
File file = null;
try {
String originalFilename = multipartFile.getOriginalFilename();
String[] filename = originalFilename.split("\\.");
file=File.createTempFile(filename[0], filename[1]);
FileOutputStream fos = new FileOutputStream(file); FileChannel channel = fos.getChannel();
channel.write(ByteBuffer.wrap(multipartFile.getBytes()));
channel.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
return file;
}
```
阅读全文