Java實現(xiàn)上傳網(wǎng)絡(luò)圖片到七牛云存儲詳解
前言
最近陽了,第二條杠紅的發(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可以使用axios或者fetch等ajax庫發(fā)送文件請求,而springboot則可以使用Spring MVC的方式來處理上傳文件請求,下面這篇文章主要給大家介紹了關(guān)于vue+springboot上傳文件、圖片、視頻及回顯到前端的相關(guān)資料,需要的朋友可以參考下2023-04-04解決分頁插件pagehelper在SpringBoot不起作用的問題
這篇文章主要介紹了解決分頁插件pagehelper在SpringBoot不起作用的問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-05-05詳解Java使用super和this來重載構(gòu)造方法
這篇文章主要介紹了詳解Java使用super和this來重載構(gòu)造方法的相關(guān)資料,這里提供實例來幫助大家理解這部分內(nèi)容,需要的朋友可以參考下2017-08-08