OSS上傳圖片 java

maven:

<!-- https://mvnrepository.com/artifact/com.aliyun.oss/aliyun-sdk-oss -->
<dependency>
    <groupId>com.aliyun.oss</groupId>
    <artifactId>aliyun-sdk-oss</artifactId>
    <version>2.4.0</version>
</dependency>
@Configuration
public class SpringConfig {

    @Autowired
    Environment env;

    @Bean(destroyMethod = "shutdown")
    public OSSClient ossClient() {
        return new OSSClient(env.getProperty("oss.userImageEndpoint"),
                env.getProperty("oss.accessKeyId"),
                env.getProperty("oss.accessKeySecret"));
    }

}
@Component
public class ImageUploader {
    private static final Logger LOG = LoggerFactory.getLogger(ImageUploader.class);
    @Autowired
    private OSSClient ossClient;
    @Value("${oss.userBucketName}")
    private String    userBucketName;
    @Value("${oss.userImageKeyPrefix}")
    private String    userImageKeyPrefix;
    @Value("${oss.userImageEndpoint}")
    private String    userImageEndpoint;
    /**
     * 上傳第三方圖片,將第三方圖片流轉爲 OSS 圖片流
     *
     * @param url 第三方圖片鏈接
     * @return OSS 生成後的鏈接
     */
    public String uploadThirdImage(String url) {
        LOG.info("要下載的圖片URL'{}'",url);
        PutObjectResult putObjectResult = null;
        try {
            InputStream inputStream = new URL(url).openStream();
            String key = userImageKeyPrefix + UUID.randomUUID().toString() + ".png";
            putObjectResult = ossClient.putObject(userBucketName, key, inputStream);
            return userImageEndpoint + "/" + key;
        } catch (IOException e) {
            // Fix by liyunfeng20170608,微信頭像有可能無法顯示,這裏轉換會出現http 400現象,拋出異常會導致用戶登錄界面出現系統異常
            // 上層進行捕獲
            throw new RuntimeException(e);
        } finally {
            if (putObjectResult != null && putObjectResult.getCallbackResponseBody() != null) {
                try {
                    putObjectResult.getCallbackResponseBody().close();
                } catch (IOException ignore) {
                }
            }
        }
    }
}
下載微信圖片到服務器,再上傳到OSS

private String mediaGet="https://api.weixin.qq.com/cgi-bin/media/get?access_token={0}&media_id={1}";
/**
 * 根據accessTokenmediaId下載微信圖片,上次到oss服務器
 * @param accessToken
 * @param mediaId
 * @return
 */
public String uploadWechatMediaImage(String accessToken, String mediaId){
    String url = MessageFormat.format(mediaGet, accessToken, mediaId);
    LOG.info("微信下載地址url'{}'",url);
    String imageName =  UUID.randomUUID().toString() + ".png";//圖片名稱
    String key = userImageKeyPrefix +imageName;
    String path=new File("").getAbsolutePath()+"/";
    PutObjectResult putObjectResult = null;
    try {
        LOG.info("開始下載");
        download(url, imageName, path+userImageKeyPrefix);
        LOG.info("下載圖片成功。。。。。");
        File file = new File(path + key);
        ObjectMetadata meta = new ObjectMetadata();// 創建上傳ObjectMetadata
        meta.setContentLength(file.length());// 必須設置ContentLength
        meta.setContentType("image/png");
        putObjectResult = ossClient.putObject(userBucketName, key, file, meta);
        if (file.exists()) {
            file.delete();
        }
        return userImageEndpoint + "/" + key;
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        if (putObjectResult != null && putObjectResult.getCallbackResponseBody() != null) {
            try {
                putObjectResult.getCallbackResponseBody().close();
            } catch (IOException ignore) {
            }
        }
    }
}
/**
 * 下載圖片到本地
 *
 * @param urlString
 * @param filename
 * @param savePath
 * @throws Exception
 */
public void download(String urlString, String filename, String savePath) throws Exception {
    LOG.info("新生成圖片名:'{}'",filename);
    LOG.info("保存到服務器路徑:'{}'",savePath);
    long start = System.currentTimeMillis();
    // 構造URL
    URL url = new URL(urlString);
    //打開鏈接
    HttpURLConnection conn = (HttpURLConnection)url.openConnection();
    //設置請求方式爲"GET"
    conn.setRequestMethod("GET");
    //超時響應時間爲5    conn.setConnectTimeout(5 * 1000);
    //通過輸入流獲取圖片數據
    InputStream inStream = conn.getInputStream();
    //得到圖片的二進制數據,以二進制封裝得到數據,具有通用性
    byte[] data = readInputStream(inStream);
    //new一個文件對象用來保存圖片,默認保存當前工程根目錄
    File imageFile = new File(savePath);
    if (!imageFile.exists() && !imageFile.isDirectory()) {
        imageFile.mkdirs();
    }
    //創建輸出流
    FileOutputStream outStream = new FileOutputStream(imageFile.getPath() + "/" + filename);
    //寫入數據
    outStream.write(data);
    //關閉輸出流
    outStream.close();
    LOG.info("下載耗時:'{}'",System.currentTimeMillis()-start);
}
private byte[] readInputStream(InputStream inStream) throws Exception{
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    //創建一個Buffer字符串
    byte[] buffer = new byte[1024];
    //每次讀取的字符串長度,如果爲-1,代表全部讀取完畢
    int len = 0;
    //使用一個輸入流從buffer裏把數據讀取出來
    while( (len=inStream.read(buffer)) != -1 ){
        //用輸出流往buffer裏寫入數據,中間參數代表從哪個位置開始讀,len代表讀取的長度
        outStream.write(buffer, 0, len);
    }
    //關閉輸入流
    inStream.close();
    //outStream裏的數據寫入內存
    return outStream.toByteArray();
}

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