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()); } } }