import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
@Component
public class MultipartFileToFileUtils {
/**
* MultipartFile 转 File
*
* @param file
* @throws Exception
*/
public static File multipartFileToFile(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();
}
return toFile;
}
//Get the stream file
private 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();
}
}
/**
* Del Local Files
* @param file
*/
public static void delteTempFile(File file) {
if (file != null) {
File del = new File(file.toURI());
del.delete();
}
}
}
Read More:
- [Solved] Spring upload file Error: Multipartfile Transferto() reported an error FileNotFoundException
- After asynchronous file import and springboot multipartfile upload, the @async asynchronous processing reports an error: nosuchfileexception
- JAVA: How to Use Multipartfile to upload Files
- SpringCloud Use openFeign Multipartfile to Upload Files Error: Current request is not a multipart request
- How to Download File via Response (Example Code)
- Java will convert Excel to list set or JSON, export excel file to local, excel import and export, easyexcel tool class
- [Solved] Read the resources resource and convert it to file error: java.io.filenotfoundexception
- How to Solve The classpathresource reads the resource file Error
- [Solved] Failed to bind properties under ‘spring.servlet.multipart.file-size-threshold‘ to
- How to Use filechannel to copy files
- Java error: unable to find or load main class (package name in source file)
- JAVA: Random access file is always garbled
- [Solved] Kafka in Windows error:java. nio. file. Filesystemexception: this file is in use by another program and cannot be accessed by the process
- How to Solve Java Runtime (class file version 53.0)ERROR
- [Solved] ln: failed to create symbolic link ‘/usr/bin/java’: File exists
- How to Solve Springboot configurate environment file Error
- Upload file error analysis standardmultiparthttpservletrequest
- [Solved] jar file Execute Error: power shell error: unable to access jarfile
- Eclipse: How to Close XML validation (xml file Error)
- Java parsing xml file encounters special symbols & will be abnormal solutions