匯入圖片

XiangdxDu發表於2024-04-23
 @PostMapping("/uploadExercise")
    public ResponseEntity<String> uploadExercise(@RequestParam MultipartFile file, @RequestParam("exercise_id") int exercise_id) throws IOException {

        String md5;

        try (InputStream inputStream = file.getInputStream()) {
            // 計算檔案的 MD5 值
            md5 = SecureUtil.md5(inputStream);
        }

        // 生成唯一標識碼
        String uuid = IdUtil.fastSimpleUUID();

        // 檔名
        String fileUUID = uuid + StrUtil.DOT + FileUtil.extName(file.getOriginalFilename());

        // 將檔案上傳到磁碟
        File uploadExerciseFile = new File(fileUploadExercisePath + fileUUID);
        file.transferTo(uploadExerciseFile);

        // 儲存在資料庫中
        Exercise saveExerciseFile = new Exercise();
        saveExerciseFile.setExercise_id(exercise_id);
        saveExerciseFile.setExercise_url("http://localhost:8081/api/exercise-show/" + fileUUID);
        saveExerciseFile.setMd5(md5);

        // 判斷運動是否被新增
        if (exerciseMapper.exerciseById(exercise_id) == null) {
            System.out.println("無資料");
        } else {
            int url1=exerciseMapper.updateExerciseUrl(saveExerciseFile);
            System.out.println("url=" + url1);
            if(url1 > 0){
                System.out.println("上傳成功");
            }else{
                System.out.println("上傳失敗");
            }
        }
        return ResponseEntity.ok(saveExerciseFile.getExercise_url());
    }

相關文章