/** * url转变为 MultipartFile对象 * @param url * @param fileName * @return * @throws Exception */private static MultipartFile createFileItem(String url, String fileName) throws Exception{ FileItem item = null; try { HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setReadTimeout(30000); conn.setConnectTimeout(30000); //设置应用程序要从网络连接读取数据 conn.setDoInput(true); conn.setRequestMethod("GET"); if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { InputStream is = conn.getInputStream(); FileItemFactory factory = new DiskFileItemFactory(16, null); String textFieldName = "uploadfile"; item = factory.createItem(textFieldName, ContentType.APPLICATION_OCTET_STREAM.toString(), false, fileName); OutputStream os = item.getOutputStream(); int bytesRead = 0; byte[] buffer = new byte[8192]; while ((bytesRead = is.read(buffer, 0, 8192)) != -1) { os.write(buffer, 0, bytesRead); } os.close(); is.close(); } } catch (IOException e) { throw new RuntimeException("文件下载失败", e); } return new CommonsMultipartFile(item);}
url转变为 MultipartFile对象
点赞
收藏