第一种方式
把读到的MultipartFile转存到本地的临时文件,然后再从本地读取这个转存的这个临时文件,从中获取文件流
// 首先
MultipartFile sourceFile;
// 处理方式
InputStream inputStream = null;
File file = null;
file = File.createTempFile("temp", null);
sourceFile.transferTo(file); //sourceFile为传入的MultipartFile
inputStream = new FileInputStream(file);
file.deleteOnExit();
第二种方式
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.apache.commons.fileupload.disk.DiskFileItem;
CommonsMultipartFile cFile = (CommonsMultipartFile) mFile;
DiskFileItem fileItem = (DiskFileItem) cFile.getFileItem();
InputStream inputStream = fileItem.getInputStream();
// 示例代码
其他
/**
* InputStream转byte[]
*/
public static byte[] getFile(final InputStream inputStream ){
//这个是重点
ByteArrayOutputStream resultByte = new ByteArrayOutputStream();
byte[] read_buf = new byte[64 * 1024];
int read_len = 0;
while ((read_len = inputStream.read(read_buf)) > 0) {
resultByte.write(read_buf, 0, read_len);
}
return resultByte.toByteArray();
}
/**
* MultipartFile 转 File
*/
public static File multipartFileToFile(MultipartFile multipartFile){
// 获取文件名
String fileName = multipartFile.getOriginalFilename();
// 获取文件后缀
String prefix=fileName.substring(fileName.lastIndexOf("."));
File excelFile = null;
try {
// 用时间作为文件名,防止生成的临时文件重复
excelFile = File.createTempFile(UUID.randomUUID().toString(), prefix);
multipartFile.transferTo(excelFile);
}catch (Exception e){
log.error("==========={}文件=================转换异常", fileName);
e.printStackTrace();
}
return excelFile;
}
/**
* 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();
}
/**
* 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();
}
}
/**
* 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();
}
}