很多时候,在对文件上传和下载的时候,内置的MultipartFile文件类型有时候并不符合我们的操作要求,需要对MultipartFile文件类型进行转换。
/**
* MultipartFile 转 File
*
* @param file
* @throws Exception
*/
public static void multipartFileToFile(@RequestParam MultipartFile file) throws Exception {
File toFile = null;
if (file.equals("") || file.getSize() <= 0) {
file = null;
} else {
InputStream ins = null;
ins = file.getInputStream();
toFile = new File(file.getOriginalFilename());
inputStreamToFile(ins, toFile);
ins.close();
}
}
/**
* File 转 MultipartFile
*
* @param file
* @throws Exception
*/
public static void fileToMultipartFile(File file) throws Exception {
FileInputStream fileInput = new FileInputStream(file);
MultipartFile toMultipartFile = new MockMultipartFile("file", file.getName(), "text/plain",
IOUtils.toByteArray(fileInput));
toMultipartFile.getInputStream();
}
/**
* InputStream 转 File
*
* @param ins
* @param file
*/
public static void inputStreamToFile(InputStream ins, File file) {
try {
OutputStream os = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
ins.close();
} catch (Exception e) {
e.printStackTrace();
}
}