JAVA 上傳文件到本地服務器


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 "";
    }
}

 


免責聲明!

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



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