1. 程式人生 > 資訊 >電視 OLED 面板價格連續三季度下跌,機構稱 Q2 跌勢將持續

電視 OLED 面板價格連續三季度下跌,機構稱 Q2 跌勢將持續

關於SpringBoot檔案上傳的記錄

  1. springboot實現檔案上傳很容易,只需要MultipartFile即可實現。
  2. 在專案中新建資料夾upload用於儲存上傳的圖片,在資料庫中儲存對應的圖片的位置。
  3. 保證檔名不重複使用uuid命名。
  4. 防止檔案過多,自定義一個刪除檔案方法。
//檔案上傳工具類
public class FileUtils {

    public static String saveFile(MultipartFile file) {

        File path = null;
        try {
            path = new File(ResourceUtils.getURL("").getPath() + "/src/main/resources/static/upload/images");
        } catch (FileNotFoundException e) {
            System.out.println("出錯了!找不到指定檔案");
            return "error";
        }

        //日期目錄
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");

        String datePath = dateFormat.format(new Date());

        //最終存放的目錄   (contextPath/datePath)
        File targetFile = new File(path, datePath);
        System.out.println("targetFile=" + targetFile);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        //獲取上傳檔案的完整名稱,包括字尾名
        String filename = file.getOriginalFilename();

        //獲取檔案字尾名
        String fileSuffix = filename.substring(filename.lastIndexOf("."));

        //通過uuid隨機產生檔名,避免檔名重複導致覆蓋
        String newFileName = UUID.randomUUID().toString() + fileSuffix;

        //最終存放的目錄及檔名
        File newTargetFile = new File(targetFile, newFileName);

        //儲存到資料庫的路徑資料
        String savePath = "/upload/images/" + datePath + "/" + newFileName;


        try {
            file.transferTo(newTargetFile);
            return savePath;
        } catch (IOException e) {
            e.printStackTrace();
            return "error";
        }
    }


    public static void deleteFile(String filename) {
        try {
            File file = new File(ResourceUtils.getURL("").getPath() + "/src/main/resources/static/" + filename);
            if (!file.isFile()) {
                System.out.println("刪除失敗!找不到指定檔案");
                return;
            }

            if (file.delete()) {
                System.out.println("刪除成功!");
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }


    @SneakyThrows
    public static void main(String[] args) {
        String filename = "/upload/images/2022/02/16/457c599c-f83f-403b-99d2-a36c69cd34f6.jpg";
        deleteFile(filename);
    }
}