目录 一、引入依赖包 二、本地文件转为MultipartFile 三、图片地址转 MultipartFile
一、引入依赖包
< ! -- 文件上传工具类 -- > < dependency> < groupId> commons- fileupload< / groupId> < artifactId> commons- fileupload< / artifactId> < version> 1.3 .3 < / version> < / dependency>
二、本地文件转为MultipartFile
public static MultipartFile pathToMultipartFile ( String picPath) throws Exception { FileItem fileItem = createFileItem ( picPath) ; MultipartFile mfile = new CommonsMultipartFile ( fileItem) ; return mfile; } public static FileItem createFileItem ( String filePath) throws Exception { FileItemFactory factory = new DiskFileItemFactory ( 16 , null ) ; String textFieldName = "textField" ; FileItem item = factory. createItem ( textFieldName, "text/plain" , true , "MyFileName" ) ; File newfile = new File ( filePath) ; int bytesRead = 0 ; byte [ ] buffer = new byte [ 8192 ] ; FileInputStream fis = null ; OutputStream os = null ; try { fis = new FileInputStream ( newfile) ; os = item. getOutputStream ( ) ; while ( ( bytesRead = fis. read ( buffer, 0 , 8192 ) ) != - 1 ) { os. write ( buffer, 0 , bytesRead) ; } } catch ( IOException e) { System . out. println ( "createFileItem:文件转换异常!" ) ; throw e; } finally { try { if ( null != os) { os. close ( ) ; } if ( null != fis) { fis. close ( ) ; } } catch ( IOException e) { System . out. println ( "createFileItem:关流异常!" ) ; throw e; } } return item; }
三、图片地址转 MultipartFile
public static MultipartFile uploadImgUrlToMultipartFile ( String url) { byte [ ] bytes = downloadPicture ( url) ; String name = "imageFile" + url. substring ( url. lastIndexOf ( "." ) ) ; MultipartFile multipartFile = getMultipartFile ( name, bytes) ; return multipartFile; } public static MultipartFile getMultipartFile ( String name, byte [ ] bytes) { MultipartFile mfile = null ; ByteArrayInputStream in = null ; try { in = new ByteArrayInputStream ( bytes) ; FileItemFactory factory = new DiskFileItemFactory ( 16 , null ) ; FileItem fileItem = factory. createItem ( "mainFile" , "text/plain" , false , name) ; IOUtils . copy ( new ByteArrayInputStream ( bytes) , fileItem. getOutputStream ( ) ) ; mfile = new CommonsMultipartFile ( fileItem) ; in. close ( ) ; } catch ( Exception e) { e. printStackTrace ( ) ; } return mfile; } private static byte [ ] downloadPicture ( String url) { URL urlConnection = null ; HttpURLConnection httpURLConnection = null ; try { urlConnection = new URL ( url) ; httpURLConnection = ( HttpURLConnection ) urlConnection. openConnection ( ) ; InputStream in = httpURLConnection. getInputStream ( ) ; byte [ ] buffer = new byte [ 1024 ] ; int len = 0 ; ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; while ( ( len = in. read ( buffer) ) != - 1 ) { out. write ( buffer, 0 , len) ; } in. close ( ) ; out. close ( ) ; return out. toByteArray ( ) ; } catch ( Exception e) { e. printStackTrace ( ) ; } finally { httpURLConnection. disconnect ( ) ; } return null ; }