欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java實現(xiàn)上傳網(wǎng)絡(luò)圖片到七牛云存儲詳解

 更新時間:2022年12月30日 09:05:36   作者:穆雄雄  
這篇文章主要為大家詳細介紹了Java如何實現(xiàn)上傳網(wǎng)絡(luò)圖片到七牛云存儲,文中的示例代碼講解詳細,具有一定的借鑒價值,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下

前言

最近陽了,第二條杠紅的發(fā)紫,真難受啊,但是吧,博客上有個bug,不解決感覺比陽了還難受。

話還是要從博客的圖片顯示不出來這里說起,當(dāng)時做的時候,在發(fā)文章這里,感覺沒有封面的話,文章會很孤單,所以就設(shè)計了個封面這塊兒。但是,封面如果太邋遢也還不如沒有。

所以我就從網(wǎng)上的一個接口里面隨機取的一些精美圖片,本來好好的,結(jié)果今天一看,那個接口報錯403了,當(dāng)時就想著,這樣做太依賴別人了,什么東西都得掌控在自己手里,不然出問題了難受的還是自己。

正好借這個機會,就重新設(shè)計了下,先從接口中取,如果接口中的圖片能看,則用這個圖片,順便將這個圖片傳至七牛云存儲中,否則就隨機從七牛云存儲中指定些圖片展示出來,這樣就不會受制于人。

效果圖

直接將圖片傳至七牛云中,給我們返回該圖片的地址。

代碼實現(xiàn)

因為七牛云上傳圖片的時候,傳遞的是MultipartFile類型,所以我們需要將網(wǎng)絡(luò)圖片utl轉(zhuǎn)換成流,然后在轉(zhuǎn)換成MultipartFile,接著使用七牛云提供的方法上傳即可。

下面我們先看看怎么將網(wǎng)絡(luò)url轉(zhuǎn)換成MultipartFile,這個代碼網(wǎng)上很多,大家可以隨便搜一個放上來就行,我這邊封裝了個工具類:FilesUtil

package com.shiyi.util;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import org.apache.http.entity.ContentType;
import org.apache.pdfbox.io.IOUtils;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author: muxiongxiong
 * @date: 2022年12月29日 15:35
 * 博客:https://blog.csdn.net/qq_34137397
 * 個人站:https://www.穆雄雄.com
 * 個人站:https://www.muxiongxiong.cn
 * @Description: 類的描述
 */
public class FilesUtil {


    /**
     * 根據(jù)地址獲得數(shù)據(jù)的輸入流
     *
     * @param strUrl 網(wǎng)絡(luò)連接地址
     * @return url的輸入流
     */
    public static InputStream getInputStreamByUrl(String strUrl) {
        HttpURLConnection conn = null;
        try {
            URL url = new URL(strUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(20 * 1000);
            final ByteArrayOutputStream output = new ByteArrayOutputStream();
            IOUtils.copy(conn.getInputStream(), output);
            return new ByteArrayInputStream(output.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (conn != null) {
                    conn.disconnect();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 將網(wǎng)絡(luò)地址轉(zhuǎn)換成MultipartFile
     * @param strUrl
     * @return
     */
    public static MultipartFile onlineAddressTransferFile(String strUrl){
        MultipartFile file = null;
        try {
            String fileName = strUrl.substring(strUrl.lastIndexOf("/") + 1);
            InputStream  stream = getInputStreamByUrl(strUrl);
            if (!ObjectUtils.isEmpty(stream)) {
                 file = new MockMultipartFile(fileName, fileName, "", stream);
                return file;
            }
        }catch (Exception exception){
            exception.printStackTrace();
        }
        return file;
    }

}

在調(diào)用的時候我們這樣調(diào):

  /**
     * 手動上傳網(wǎng)絡(luò)圖片
     */
    @GetMapping(value = "/uploadFm")
    public ResponseResult uploadFm(){
        MultipartFile multipartFile =  FilesUtil.onlineAddressTransferFile("https://img-community.csdnimg.cn/images/86f32eac875e42af9ed9e91b809dc7d8.png");
        return cloudOssService.upload(multipartFile);
    }

剩下的就是七牛云里面的方法了,這邊一起放上來吧:

CloudOssService接口代碼:

package com.shiyi.service;

import com.shiyi.common.ResponseResult;
import org.springframework.web.multipart.MultipartFile;

public interface CloudOssService {
    /**
     * 上傳
     * @param file 文件
     * @return
     */
    ResponseResult upload(MultipartFile file);

    /**
     * 批量刪除文件
     * @param key 文件名
     * @return
     */
    ResponseResult delBatchFile(String ...key);
}

CloudOssServiceImpl實現(xiàn)類,主要是實現(xiàn)CloudOssService接口的:

package com.shiyi.service.impl;


import com.shiyi.common.ResponseResult;

import com.shiyi.enums.FileUploadModelEnum;
import com.shiyi.service.CloudOssService;
import com.shiyi.service.SystemConfigService;
import com.shiyi.strategy.context.FileUploadStrategyContext;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Objects;

@Service
@RequiredArgsConstructor
public class CloudOssServiceImpl implements CloudOssService {

    private final SystemConfigService systemConfigService;

    private final FileUploadStrategyContext fileUploadStrategyContext;

    private String strategy;

    /**
     * 上傳文件
     * @param file
     * @return
     */
    @Override
    public ResponseResult upload(MultipartFile file) {
        if (file.getSize() > 1024 * 1024 * 10) {
            return ResponseResult.error("文件大小不能大于10M");
        }
        //獲取文件后綴
        String suffix = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        if (!"jpg,jpeg,gif,png".toUpperCase().contains(suffix.toUpperCase())) {
            return ResponseResult.error("請選擇jpg,jpeg,gif,png格式的圖片");
        }
        getFileUploadWay();
        String key = fileUploadStrategyContext.executeFileUploadStrategy(strategy, file, suffix);
        return ResponseResult.success(key);
    }


    /**
     * 刪除文件
     * @param key
     * @return
     */
    @Override
    public ResponseResult delBatchFile(String ...key) {
        getFileUploadWay();
        Boolean isSuccess = fileUploadStrategyContext.executeDeleteFileStrategy(strategy, key);
        if (!isSuccess) {
            return ResponseResult.error("刪除文件失敗");
        }
        return ResponseResult.success();
    }

    private void getFileUploadWay() {
        strategy = FileUploadModelEnum.getStrategy(systemConfigService.getCustomizeOne().getFileUploadWay());
    }
}

最后是文件上傳策略上下文類:

package com.shiyi.strategy.context;

import com.shiyi.strategy.FileUploadStrategy;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;


/**
 * @apiNote 文件上傳策略上下文
 */
@Service
@RequiredArgsConstructor
public class FileUploadStrategyContext {

    private final Map<String, FileUploadStrategy> fileUploadStrategyMap;

    /**
     * 執(zhí)行文件上傳策略
     *
     * @param file 文件對象
     * @return {@link String} 文件名
     */
    public String executeFileUploadStrategy(String fileUploadMode, MultipartFile file,String suffix) {
         return fileUploadStrategyMap.get(fileUploadMode).fileUpload(file,suffix);
    }

    /**
     * 刪除文件策略
     * @param fileUploadMode
     * @param key
     * @return
     */
    public Boolean executeDeleteFileStrategy(String fileUploadMode,String ...key) {
         return fileUploadStrategyMap.get(fileUploadMode).deleteFile(key);
    }
}

QiNiuUploadStrategyImpl實現(xiàn)類的代碼:

package com.shiyi.strategy.imp;

import com.alibaba.fastjson.JSON;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.BatchStatus;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.util.Auth;
import com.shiyi.entity.SystemConfig;
import com.shiyi.enums.QiNiuAreaEnum;
import com.shiyi.service.SystemConfigService;
import com.shiyi.strategy.FileUploadStrategy;
import com.shiyi.util.UUIDUtils;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;


@Service("qiNiuUploadStrategyImpl")
@RequiredArgsConstructor
public class QiNiuUploadStrategyImpl implements FileUploadStrategy {

    private final Logger logger = LoggerFactory.getLogger(QiNiuUploadStrategyImpl.class);

    private final SystemConfigService systemConfigService;
    private String qi_niu_accessKey;
    private String qi_niu_secretKey;
    private String qi_niu_bucket;
    private Region region;
    private String qi_niu_url;

    @PostConstruct
    private void init(){
        SystemConfig systemConfig = systemConfigService.getCustomizeOne();
        qi_niu_accessKey = systemConfig.getQiNiuAccessKey();
        qi_niu_secretKey = systemConfig.getQiNiuSecretKey();
        qi_niu_bucket = systemConfig.getQiNiuBucket();
        qi_niu_url = systemConfig.getQiNiuPictureBaseUrl();
        region = QiNiuAreaEnum.getRegion(systemConfig.getQiNiuArea());
    }

    public void list() {
        Configuration configuration = new Configuration(region);
        Auth auth = Auth.create(qi_niu_accessKey, qi_niu_secretKey);
        BucketManager bucketManager = new BucketManager(auth,configuration);
        BucketManager.FileListIterator fileListIterator = bucketManager.createFileListIterator(qi_niu_bucket, null, 1000, null);
        while (fileListIterator.hasNext()) {
            FileInfo[] next = fileListIterator.next();
            for (FileInfo fileInfo : next) {
                logger.info("文件打印開始,文件名:{}",qi_niu_url + fileInfo.key);
                logger.info("文件類別打印開始,類別:{}",fileInfo.mimeType);
                logger.info("文件大小打印開始,大小:{}",fileInfo.fsize);
            }
        }
    }

    /**
     * 七牛云文件上傳
     * @param file 文件
     * @param suffix 后綴
     * @return
     */
    @Override
    public String fileUpload(MultipartFile file,String suffix) {
        String key = null;
        //構(gòu)造一個帶指定 Region 對象的配置類
        Configuration cfg = new Configuration(region);
        //...其他參數(shù)參考類注釋
        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上傳憑證,然后準(zhǔn)備上傳
        Auth auth = Auth.create(qi_niu_accessKey, qi_niu_secretKey);
        String upToken = auth.uploadToken(qi_niu_bucket);
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
            //這里需要處理一下,不能讓每次上去都是個UUID的文件名
            Response response = uploadManager.put(inputStream, "blog/"+UUIDUtils.getUuid() + "." + suffix, upToken,null,null);
            //解析上傳成功的結(jié)果
            DefaultPutRet putRet = JSON.parseObject(response.bodyString(),DefaultPutRet.class);
            key =  qi_niu_url + putRet.key;
        } catch (QiniuException ex) {
            Response r = ex.response;
            logger.error("QiniuException:{}",r.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return key;
    }

    /**
     * 批量刪除文件
     * @return
     */
    @Override
    public Boolean deleteFile(String ...keys) {
        //構(gòu)造一個帶指定 Region 對象的配置類
        Configuration cfg = new Configuration(Region.region2());
        //...其他參數(shù)參考類注釋
        Auth auth = Auth.create(qi_niu_accessKey, qi_niu_secretKey);
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            BucketManager.BatchOperations batchOperations = new BucketManager.BatchOperations();
            batchOperations.addDeleteOp(qi_niu_bucket, keys);
            Response response = bucketManager.batch(batchOperations);
            BatchStatus[] batchStatusList = response.jsonToObject(BatchStatus[].class);
            for (int i = 0; i < keys.length; i++) {
                BatchStatus status = batchStatusList[i];
                String key = keys[i];
                System.out.print(key + "\t");
                if (status.code == 200) {
                    System.out.println("delete success");
                } else {
                    System.out.println(status.data.error);
                }
            }
            return true;
        } catch (QiniuException ex) {
            System.err.println(ex.response.toString());
            return false;
        }
    }

}

然后我們從接口里面直接調(diào)用即可上傳上去。

到此這篇關(guān)于Java實現(xiàn)上傳網(wǎng)絡(luò)圖片到七牛云存儲詳解的文章就介紹到這了,更多相關(guān)Java上傳圖片到七牛云存儲內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • vue+springboot上傳文件、圖片、視頻及回顯到前端詳解

    vue+springboot上傳文件、圖片、視頻及回顯到前端詳解

    一般來說vue可以使用axios或者fetch等ajax庫發(fā)送文件請求,而springboot則可以使用Spring MVC的方式來處理上傳文件請求,下面這篇文章主要給大家介紹了關(guān)于vue+springboot上傳文件、圖片、視頻及回顯到前端的相關(guān)資料,需要的朋友可以參考下
    2023-04-04
  • 解決分頁插件pagehelper在SpringBoot不起作用的問題

    解決分頁插件pagehelper在SpringBoot不起作用的問題

    這篇文章主要介紹了解決分頁插件pagehelper在SpringBoot不起作用的問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-05-05
  • Java基礎(chǔ)第三篇 構(gòu)造器與方法重載

    Java基礎(chǔ)第三篇 構(gòu)造器與方法重載

    顯式初始化要求我們在寫程序時就確定初始值,這有時很不方便。我們可以使用構(gòu)造器(constructor)來初始化對象。構(gòu)造器可以初始化數(shù)據(jù)成員,還可以規(guī)定特定的操作。這些操作會在創(chuàng)建對象時自動執(zhí)行。下面文字將對該內(nèi)容做詳細介紹,需要的小伙伴請參考
    2021-09-09
  • Java執(zhí)行hadoop的基本操作實例代碼

    Java執(zhí)行hadoop的基本操作實例代碼

    這篇文章主要介紹了Java執(zhí)行hadoop的基本操作實例代碼的相關(guān)資料,需要的朋友可以參考下
    2017-04-04
  • 簡潔實用的Java Base64編碼加密異常處理類代碼

    簡潔實用的Java Base64編碼加密異常處理類代碼

    這篇文章主要介紹了簡潔實用的Java Base64編碼加密異常處理類代碼,有一定的實用價值,需要的朋友可以參考下
    2014-07-07
  • 詳解Java如何通過Socket實現(xiàn)查詢IP

    詳解Java如何通過Socket實現(xiàn)查詢IP

    在本文中,我們來學(xué)習(xí)下如何找到連接到服務(wù)器的客戶端計算機的IP地址。我們將創(chuàng)建一個簡單的客戶端-服務(wù)器場景,讓我們探索用于TCP/IP通信的java.net?API,感興趣的可以了解一下
    2022-10-10
  • 淺談springBoot注解大全

    淺談springBoot注解大全

    本篇文章主要介紹了淺談springBoot注解大全,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-03-03
  • 如何用struts調(diào)用支付寶接口

    如何用struts調(diào)用支付寶接口

    以下為大家介紹如何用struts調(diào)用支付寶接口的例子。
    2013-04-04
  • java之super關(guān)鍵字用法實例解析

    java之super關(guān)鍵字用法實例解析

    這篇文章主要介紹了java之super關(guān)鍵字用法實例解析,較為詳細的分析了super關(guān)鍵字的用法及內(nèi)存分布,需要的朋友可以參考下
    2014-09-09
  • 詳解Java使用super和this來重載構(gòu)造方法

    詳解Java使用super和this來重載構(gòu)造方法

    這篇文章主要介紹了詳解Java使用super和this來重載構(gòu)造方法的相關(guān)資料,這里提供實例來幫助大家理解這部分內(nèi)容,需要的朋友可以參考下
    2017-08-08

最新評論