头疼,不废话直接上代码
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
1,网络图片转InputStream
InputStream inputStream = getImageStream("http://192.168.111.111:2333/pic?xxxxxxxx");
* 获取网络图片流
* @param url
* @return
public static InputStream getImageStream(String url) {
try {
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setReadTimeout(5000);
connection.setConnectTimeout(5000);
connection.setRequestMethod("GET");
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream inputStream = connection.getInputStream();
return inputStream;
} catch (IOException e) {
System.out.println("获取网络图片出现异常,图片路径为:" + url);
e.printStackTrace();
return null;
2,InputStream转MultipartFile
1)MockMultipartFile
MultipartFile multipartFile = new MockMultipartFile("xxxx.jpg","xxxx.jpg", MediaType.MULTIPART_FORM_DATA_VALUE, inputStream);
2) CommonsMultipartFile
public void testOSSServiceImport(){
File file = new File("xxxx.jpg");
DiskFileItem fileItem = (DiskFileItem) new DiskFileItemFactory().createItem("file",
MediaType.ALL_VALUE, true, file.getName());
try (InputStream input = new FileInputStream(file); OutputStream os = fileItem.getOutputStream()) {
IOUtils.copy(input, os);
} catch (Exception e) {
throw new IllegalArgumentException("Invalid file: " + e, e);
MultipartFile multi = new CommonsMultipartFile(fileItem);