java實現網頁瀏覽圖片轉可下載的文件流

 java 原生api實現網頁瀏覽圖片轉成可下載的流信息

/**
 * @author zhq.xiang
 */
public class FileUtils {
    private static Logger logger = LoggerFactory.getLogger(FileUtils.class);

    /**
     * 獲取網絡url文件流
     *
     * @param path 文件url
     * @return InputStream 注:該流對象逃逸,注意關閉流
     */
    public static InputStreamDto read2InputStreamDto(String path) {
        try {
            InputStreamDto inputStreamDto = new InputStreamDto();
            if (StringUtils.isBlank(path)) {
                return null;
            } else {
                inputStreamDto.setFormat(getFileFormat(path));
            }
            URL url = new URL(path);
            URLConnection urlConn = url.openConnection();
            urlConn.connect();
            HttpURLConnection httpConn = (HttpURLConnection)urlConn;
            int httpResult = httpConn.getResponseCode();
            if (httpResult != HttpURLConnection.HTTP_OK) {
                logger.error("無法連接到");
                return null;
            }
            int contentLength = httpConn.getContentLength();
            inputStreamDto.setContentLength(contentLength);
            inputStreamDto.setInputStream(httpConn.getInputStream());

            return inputStreamDto;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 關閉文件流
     *
     * @param inputStreamDto
     */
    public static void close(InputStreamDto inputStreamDto) {
        if (inputStreamDto != null && inputStreamDto.getInputStream() != null) {
            try {
                inputStreamDto.getInputStream().close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 獲取文件的格式
     *
     * @param path
     * @return
     */
    private static String getFileFormat(String path) {
        if (StringUtils.isBlank(path) || path.lastIndexOf(Constants.SYMBOL_DOT) < 0) {
            return null;
        }
        int startIndex = path.lastIndexOf(Constants.SYMBOL_DOT);
        int endIndex = path.lastIndexOf(Constants.SYMBOL_QUESTION);
        return endIndex < 0 ? path.substring(startIndex).replaceAll("\\" + Constants.SYMBOL_DOT, Constants.SYMBOL_EMPTY)
            :
                path.substring(startIndex, endIndex).replaceAll("\\" + Constants.SYMBOL_DOT, Constants.SYMBOL_EMPTY);
    }


}
/**
 * @author zhq.xiang
 */
@Data
public class InputStreamDto {
    private String format;
    private InputStream inputStream;
    private Integer contentLength;
}
/**
 * @author zhq.xiang
 */
public class Constants {
    public static final String SYMBOL_DOT = ".";
    public static final String SYMBOL_EMPTY = "";
    public static final String SYMBOL_QUESTION = "?";
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章