CommonsMultipartFile 轉為 File 類型


1、我們可以查看CommonsMultipartFile的源碼發現有這樣一個方法

 

@Override
    public InputStream getInputStream() throws IOException {
        if (!isAvailable()) {
            throw new IllegalStateException("File has been moved - cannot be read again");
        }
        InputStream inputStream = this.fileItem.getInputStream();
        return (inputStream != null ? inputStream : StreamUtils.emptyInput());
    }

2、我們創建CommonsMultipartFile 對象

 

CommonsMultipartFile shopImg = null; //注意啊,這里你要傳的CommonsMultipartFile 參數自己通過commfile去接收就行

3、調用轉化方法

 


inputStreamToFile(commfile.getInputStream(), file); //getInputStream是CommonsMultipartFile的方法(文件轉化)

 

4、我們創建轉化方法

 

private static void inputStreamToFile(InputStream ins,File file) {
        FileOutputStream os = null;
        try {
            os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[1024];
            while ((bytesRead = ins.read(buffer)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
        } catch (Exception e) {
            throw new RuntimeException("調用inputStreamToFile異常" +e.getMessage());
        }finally {
            try {
                if (os != null) {
                    os.close();
                }
                if (ins != null) {
                    ins.close();
                }
            } catch (Exception e) {
                throw new RuntimeException("調用inputStreamToFile異常" +e.getMessage());
            }
        }
    }

 


免責聲明!

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



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