03.java實現文件上傳的工具類及xml配置

/*
 *@ClassName:FileUpLoad
 *@Author:Arvin_yuan
 *@Date:2020/3/1 20:55
 *@Description:TODO
 */

import org.apache.commons.io.IOUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

public class FileUpLoad {

    public static String upload(String parentPath, MultipartFile fileImage){

        //若是沒有上傳文件就爲null
        if (fileImage == null) {
            return null;
        }
        InputStream is = null;
        String fileName = null;
        FileOutputStream os = null;
        try {
            //獲取輸入流
            is = fileImage.getInputStream();
            //獲取文件名
            fileName = fileImage.getOriginalFilename();
            //文件名處理,加上一串隨機數
            fileName = UUID.randomUUID().toString().replaceAll("-","") + fileName;
            //根據文件名和父路徑獲取文件
            File file = new File(parentPath, fileName);
            //獲取輸出流
            os = new FileOutputStream(new File(parentPath, fileName));
            //進行復制
            IOUtils.copy(is,os);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (os != null) {
                    os.close();
                }
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return  fileName;
    }
}
<!-- 定義文件上傳解析器 -->
    <bean id="multipartResolver"       
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 設定默認編碼 -->
        <property name="defaultEncoding" value="UTF-8"></property>
        <!-- 設定文件上傳的最大值5MB,5*1024*1024 -->
        <property name="maxUploadSize" value="5242880"></property>
    </bean>
相關文章
相關標籤/搜索