# **[JAVA] 讀取使用者上傳的檔案進資料庫,但不保留(暫存)檔案** ###### tags: `Java` `工作筆記` ### 坑點 通常在讀取文檔、依分隔號切割字串轉成entity存入資料庫時 一般會將前端上傳的MultipartFile轉型為File,再使用File系列的API去處理文檔 ```java= // MultipartFile轉型為File private File convertMultiPartToFile(MultipartFile file ) throws IOException { File convFile = new File(Objects.requireNonNull(file.getOriginalFilename())); FileOutputStream fos = new FileOutputStream( convFile ); fos.write( file.getBytes() ); fos.close(); return convFile; } // File資料處理(略) ``` 但使用File系列的API時,會在專案的根目錄建立使用者上傳的檔案 在測試環境若不想要保留該檔案時,只須在最後寫好刪除檔案的程式碼即可。 但公司的正式環境是受到層層控管的OpenShift平台,會因為沒有權限無法做刪除檔案的動作... 因此要使用資料流的方式來處理 ### 作法 使用MultipartFile類內的API getBytes()去取得byte[] 再去轉換成InputStream 轉換成InputStreamReader的時候必須==注意編碼==的問題,不然中文的部分會有亂碼、切割符失靈的問題 資料來源格式: ![Uploading file..._xpi7jppzh]() 我的檔案來源是UTF-8,因此charset設為`StandardCharsets.UTF_8` 切割符為"|"符號,記得要跳脫字元 ```java= //file為前端傳來的文檔,型態:MultipartFile public List<Employee> readCsvAndInsertIntoDB(MultipartFile file) throws IOException { List<Employee> employeeList = new ArrayList<>(); //存最先匯入employee.csv byte [] byteArr = file.getBytes(); InputStream is = new ByteArrayInputStream(byteArr); InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8); BufferedReader br = new BufferedReader(isr); String line = ""; final String delimiter = "\\|"; while ((line = br.readLine()) != null) { Employee e = new Employee(); String[] token = line.split(delimiter); e.setApplBatchNo(token[0]); e.setArriveDate(token[1]); e.setArriveNo(token[2]); e.setIdn(token[3]); e.setName(token[4]); e.setBornDate((Integer.parseInt(token[5].substring(0, 3)) + 1911) + token[5].substring(3)); //轉為西元生日字串 } return employeeRepository.saveAll(employeeList); } ```