1. 程式人生 > 其它 >網路圖片轉InputStream,網路圖片轉MultipartFile,InputStream轉MultipartFile

網路圖片轉InputStream,網路圖片轉MultipartFile,InputStream轉MultipartFile

頭疼,不廢話直接上程式碼

<!-- 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);

}
zzzzzzzzzzzz