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:
- Extracting JDBC tool class: JDBC utils
- Explicit and implicit conversion of Java data type
- How to convert a Java string into a number (stringtonumber)
- How to Close the Current Form in JAVA Swing
- JAVA 8: How to Convert List to Map
- JAVA: Random access file is always garbled
- Abstract method and static method of java interface
- Ternary operator in Java?: error: not a statement
- Java — for loop printing graphics (loop structure)
- Java error prompt….. cannot be resolved
- Problems and causes of Java’s main function format (public static void main (string args()))
- Jtextfield cannot be displayed normally when added to JPanel
- The number of control threads and concurrency number of concurrent executor of Java starting gun
- Xdoc generates API documents based on Java annotations
- Caused by: java.lang.IllegalStateException (How to Fix)
- JAVE: LeetCode(189) Rotate Array
- [Fixed] Disgusting bug Error:Failed to Load project configuration: cannot parse filemessage: content is not allowed in the preface.
- Conversion of two data types in Java
- Mybatis single parameter pass in exception (How to Fix)
- Android startup page (solve the problem of starting black and white screen)