MultipartFile objects use

In the usual business development process, uploading and downloading files is a very common scenario. Spring MVC provides direct support for file uploads, which is implemented by MultipartResolver. Spring MVC uses Apache Commons FileUpload technology to implement a MultipartResolver implementation class - CommonsMultipartResolver. Therefore, the file upload of Spring MVC needs to rely on the component of Apache Commons FileUpload.

Spring Mvc will bind the uploaded file to the MultipartFile object. MultipartFile provides methods to obtain uploaded file content, file name, etc. The file can also be stored locally through the transferTo() method.

Common method table of MultipartFile object:

MultipartFile common methods
method name effect
byte[] getBytes() Get file data
String getContentType[] Get the file MIME type, such as image/jpeg, etc.
InputStream getInputStream() get file stream
String getName() Get the name of the file component in the form
String getOriginalFilename() Get the original name of the uploaded file
Long getSize() Get the byte size of the file in byte
boolean isEmpty() Check if there is an uploaded file
void transferTo(File dest)

Save uploaded files to a directory file

Get uploaded file and save local example:

 private String dirPath = "D:/source";
    
 public void fileUpload(MultipartFile picFile,String folderName) throws IOException{
        //获取文件原始名以获取它的文件后缀
        String fileName = picFile.getOriginalFilename();
        //获取"."后的后缀名
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //使用UUID.randomUUID()生成一个全局唯一的字符串
        fileName = UUID.randomUUID()+suffix;
        File dirFile = new File(dirPath);
        if (!dirFile.exists()){
            dirFile.mkdirs();
        }
        String filePath = dirPath + "/"+folderName + "/"+ fileName;
        File dirFile2=new File(filePath);
        if (!dirFile2.exists()){
            dirFile2.mkdirs();
        }
        //将文件保存到本地
        picFile.transferTo(dirFile2);
 }

Guess you like

Origin blog.csdn.net/qq_43780761/article/details/126564391