Java上傳圖片工具類


import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 圖片上傳工具類
 */
public class ImageUploadUtil {


    public static String uploadFile(@RequestParam("file") MultipartFile file, String strPath) throws IOException {
        String fileName = file.getOriginalFilename();//獲取文件名
        fileName = getFileName(fileName);
        String filepath = getUploadPath(strPath);
        if (!file.isEmpty()) {
            try (BufferedOutputStream out = new BufferedOutputStream(
                    new FileOutputStream(new File(filepath + File.separator + fileName)))) {
                out.write(file.getBytes());
                out.flush();

                return fileName;
            } catch (FileNotFoundException e) {
                return "error";//( "上傳文件失敗 FileNotFoundException:" + e.getMessage());
            } catch (IOException e) {
                return "error";//( "上傳文件失敗 IOException:" + e.getMessage());
            }
        } else {
            return "error";//( "上傳文件失敗,文件為空");
        }
    }

    /**
     * 文件名后綴前添加一個時間戳
     */
    private static String getFileName(String fileName) {
        int index = fileName.lastIndexOf(".");
        final SimpleDateFormat sDateFormate = new SimpleDateFormat("yyyymmddHHmmss");  //設置時間格式
        String nowTimeStr = sDateFormate.format(new Date()); // 當前時間
        fileName = fileName.substring(0, index) + "_" + nowTimeStr + fileName.substring(index);
        return fileName;
    }

    /**
     * 獲取當前系統路徑
     */
    private static String getUploadPath(String strPath) throws IOException {
      
        File file = new File(strPath);
        File fileParent = file.getParentFile();
        if (!fileParent.exists()) {
            fileParent.mkdirs();
        }
        if (!file.exists()) file.mkdirs();

        return file.getAbsolutePath();

    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM