JAVA 上傳檔案到本地伺服器
阿新 • • 發佈:2021-12-02
import java.io.*; public class FileUpload { /** * * @param file 檔案流 * @param destFilePath 儲存到本地的目錄路徑 * @return */ public static String upload(MultipartFile file, String destFilePath) { InputStream inputStream = null; FileOutputStream fileOutputStream= null; try { String fileName = file.getOriginalFilename(); String[] split = fileName.split("\\."); inputStream = file.getInputStream(); // 資料緩衝 byte[] buffer = new byte[1024 * 1024]; //讀取到的資料長度 int len;// 輸出的檔案流儲存到本地檔案 File tempFile = new File(destFilePath); if (!tempFile.exists()) { tempFile.mkdirs(); } //重新命名 fileName = Math.random() +"."+ split[split.length-1]; fileOutputStream = new FileOutputStream(tempFile.getPath() + File.separator + fileName);// 開始讀取 while ((len = inputStream.read(buffer)) != -1) { fileOutputStream.write(buffer, 0, len); } return fileName; } catch (IOException e) { e.printStackTrace(); } finally { // 完畢,關閉所有連結 try { fileOutputStream.close(); inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } return ""; } }