当前位置:网站首页>22-07-05 upload of qiniu cloud storage pictures and user avatars
22-07-05 upload of qiniu cloud storage pictures and user avatars
2022-07-06 20:05:00 【£ small feather】
Where to save the uploaded files
The way 1. The server where the current project is located . But not so good , There are a lot of problems
Question 1 : Will occupy tomcat Hard disk space for , influence tomcat Operating efficiency ;
Question two : Files uploaded by users are easy to lose (clean, Will be able to target Delete )
Question 3 : Data inconsistency will occur in the cluster environment .( Upload avatar upload only a certain server )
The way 2. Upload to a special file storage server ,tomcat It's the application server , To deploy the application
2.1FASTDFS、HDFS Build your own
2.2 Buy third-party cloud storage :
Alibaba cloud 、 Baidu cloud 、 Tencent cloud 、 Qiniuyun ( The vision is perfect , video 、 picture )
Use the object storage service provided by qiniu cloud to store pictures
After registering and logging in successfully :
First step : Create object storage space
Click new storage space in resource management
The page pops up : Fill in the information
You can create multiple storage spaces , Each storage space is independent of each other
The second step : View storage space information
After the storage space is created , The created storage space name will be displayed in the storage space list menu on the left , Click the storage space name to view the relevant information of the current storage space
Switch tab Page to - file management
Qiniu cloud Developer Center
You can learn how to operate the qiniu cloud service through the developer center provided by qiniu cloud , Address : Seven cow developer center
Object storage - Seven cow developer center Click on the object store , Jump to the object store development page
Write an introductory case :
First step : Import jar package :
<!-- Qiniu cloud service platform , Third party service ( Image upload )-->
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
</dependency>
The second step : authentication
our AK and SK Where to? ?
Later Java This pair will be used in the code AK、SK Of , Just come here and copy it
Upload files :
There are cases on the official website , I am imitating the test code written there
public void testUpload(){
// Construct a belt designation Zone Object configuration class
Configuration cfg = new Configuration(Zone.zone2());
// Create a file upload manager object
UploadManager uploadManager = new UploadManager(cfg);
//... Generate upload credentials , Then prepare to upload
// Your own AccessKey
String accessKey = "5awGQ0oY-NJUOECgxTnOQOHOG66W8wCvBJChUqmM";
// Your own SecretKey
String secretKey = "pz_xQZbTrhFErQcGaeCLn-tkq_1F5uXQDCBo_2tc";
// The name of your own space
String bucket = "shfxa0328-xym";
// If it is Windows Under the circumstances , The format is D:\\qiniu\\test.png
String localFilePath = "D:/qiniu/test.jpg";
///key Indicates the name of the file uploaded to qiniu cloud , Default does not specify key Under the circumstances , Based on the content of the document hash Value as filename
String key = null;
// authentication
Auth auth = Auth.create(accessKey, secretKey);
// Create a file upload flag token
String upToken = auth.uploadToken(bucket);
try {
// Upload files
Response response = uploadManager.put(localFilePath, key, upToken);
// Analyze the result of successful upload
DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
System.out.println(putRet.key);
System.out.println(putRet.hash);
} catch (QiniuException ex) {
Response r = ex.response;
System.err.println(r.toString());
try {
System.err.println(r.bodyString());
} catch (QiniuException ex2) {
//ignore
}
}
}
Cast spells before running , Configure here
function , The console prints as follows
You can see on the seven cattle cloud that we uploaded the picture successfully , And the file name is the same as the result printed by our console
Click the file details on the right , You can see the map information of this file
Deletion of files
public void testDelete(){
// Construct a belt designation Zone Object configuration class
Configuration cfg = new Configuration(Zone.zone2());
// Your own AccessKey
String accessKey = "5awGQ0oY-NJUOECgxTnOQOHOG66W8wCvBJChUqmM";
// Your own SecretKey
String secretKey = "pz_xQZbTrhFErQcGaeCLn-tkq_1F5uXQDCBo_2tc";
// The name of your own space
String bucket = "shfxa0328-xym";
// Name of the file to be deleted
String key = "FnATf109bsayb0tYiZKgoHn96lQT";
Auth auth = Auth.create(accessKey, secretKey);
BucketManager bucketManager = new BucketManager(auth, cfg);
try {
bucketManager.delete(bucket, key);
} catch (QiniuException ex) {
// If something goes wrong , Description deletion failed
System.err.println(ex.code());
System.err.println(ex.response.toString());
}
}
Check seven cattle cloud , The file was indeed deleted
Wrapper utility class QiniuUtils
This tool class has 3 It needs to be modified
public class QiniuUtils {
private static String accessKey = "5awGQ0oY-NJUOECgxTnOQOHOG66W8wCvBJChUqmM";
private static String secretKey = "pz_xQZbTrhFErQcGaeCLn-tkq_1F5uXQDCBo_2tc";
private static String bucket = "shfxa0328-xym";
public static void upload2Qiniu(String filePath,String fileName){
// Construct a belt designation Zone Object configuration class
Configuration cfg = new Configuration(Zone.zone2());
UploadManager uploadManager = new UploadManager(cfg);
Auth auth = Auth.create(accessKey, secretKey);
String upToken = auth.uploadToken(bucket);
try {
Response response = uploadManager.put(filePath, fileName, upToken);
// Analyze the result of successful upload
DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
} catch (QiniuException ex) {
Response r = ex.response;
try {
System.err.println(r.bodyString());
} catch (QiniuException ex2) {
//ignore
}
}
}
// Upload files
public static void upload2Qiniu(byte[] bytes, String fileName){
// Construct a belt designation Zone Object configuration class
Configuration cfg = new Configuration(Zone.zone2());
//... Refer to class notes for other parameters
UploadManager uploadManager = new UploadManager(cfg);
// Default does not specify key Under the circumstances , Based on the content of the document hash Value as filename
String key = fileName;
Auth auth = Auth.create(accessKey, secretKey);
String upToken = auth.uploadToken(bucket);
try {
Response response = uploadManager.put(bytes, key, upToken);
// Analyze the result of successful upload
DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
System.out.println(putRet.key);
System.out.println(putRet.hash);
} catch (QiniuException ex) {
Response r = ex.response;
System.err.println(r.toString());
try {
System.err.println(r.bodyString());
} catch (QiniuException ex2) {
//ignore
}
}
}
// Delete file
public static void deleteFileFromQiniu(String fileName){
// Construct a belt designation Zone Object configuration class
Configuration cfg = new Configuration(Zone.zone2());
String key = fileName;
Auth auth = Auth.create(accessKey, secretKey);
BucketManager bucketManager = new BucketManager(auth, cfg);
try {
bucketManager.delete(bucket, key);
} catch (QiniuException ex) {
// If something goes wrong , Description deletion failed
System.err.println(ex.code());
System.err.println(ex.response.toString());
}
}
public static String getUrl(String uuidName) {
return "http://rejg8ksr8.hn-bkt.clouddn.com/" + uuidName;
}
}
We realize a function of uploading avatars
Front page :
<form id="ec" th:action="@{/admin/upload/{id}(id=${id})}" method="post" enctype="multipart/form-data" class="form-horizontal">
<div class="form-group">
<label class="col-sm-2 control-label"> Upload your avatar :</label>
<div class="col-sm-10">
<input type="file" name="file" id="file" class="form-control" readonly/>
</div>
</div>
<div class="hr-line-dashed"></div>
<div class="form-group">
<div class="col-sm-4 col-sm-offset-2 text-right">
<button class="btn btn-primary" type="submit"> determine </button>
<button class="btn btn-white" type="button" onclick="opt.closeWin();" value=" Cancel "> Cancel </button>
</div>
</div>
The effect on the page is as follows
After selecting the avatar and clicking OK, such a piece of code will be executed :
@PostMapping("/upload/{id}")
public String upload(@PathVariable("id") Long id, @RequestParam("file") MultipartFile multipartFile, Model model) throws IOException {
//id It's the user's id
//1. Upload the picture to qiniu cloud
// Generate a unique file name
String originalFilename = multipartFile.getOriginalFilename();
String uuidName = FileUtil.getUUIDName(originalFilename);
QiniuUtils.upload2Qiniu(multipartFile.getBytes(),uuidName);
//2. Save the picture information to the database
//2.1 Get the url
String headUrl = QiniuUtils.getUrl(uuidName);
//2.2 Encapsulate information to Admin
Admin admin = new Admin();
admin.setId(id);
admin.setHeadUrl(headUrl);
//2.3 to update admin
adminService.update(admin);
//3. The success page is displayed
return successPage(model," Upload the avatar successfully ");
}
In the database acl_admin In the table head_url The fields have indeed changed
Go to the seven cattle cloud , You can also see the successful avatars we uploaded
What to pay attention to : Must be in spring-mvc Open the file upload parser in the configuration file of
<!-- File parser -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- Set the maximum file upload value to 100MB,100*1024*1024 -->
<property name="maxUploadSize" value="104857600" />
<!-- Set the maximum value of writing memory when uploading files , If less than this parameter, no temporary file will be generated , The default is 10240 -->
<property name="maxInMemorySize" value="4096" />
<!-- Set the default encoding -->
<property name="defaultEncoding" value="UTF-8"/>
</bean>
边栏推荐
- [calculating emotion and thought] floor sweeper, typist, information panic and Oppenheimer
- 技术分享 | 抓包分析 TCP 协议
- RT-Thread 组件 FinSH 使用时遇到的问题
- PowerPivot - DAX (first time)
- rt-thread i2c 使用教程
- Tencent cloud database public cloud market ranks top 2!
- 某东短信登录复活 安装部署教程
- Analysis of rainwater connection
- 350. Intersection of two arrays II
- 爬虫(14) - Scrapy-Redis分布式爬虫(1) | 详解
猜你喜欢
(3) Web security | penetration testing | basic knowledge of network security construction, IIS website construction, EXE backdoor generation tool quasar, basic use of
Classic 100 questions of algorithm interview, the latest career planning of Android programmers
Understand yolov1 Part II non maximum suppression (NMS) in prediction stage
Cesium 点击绘制圆形(动态绘制圆形)
新一代垃圾回收器—ZGC
Selenium advanced operations
The "white paper on the panorama of the digital economy" has been released with great emphasis on the digitalization of insurance
腾讯T3手把手教你,真的太香了
Vscode debug run fluent message: there is no extension for debugging yaml. Should we find yaml extensions in the market?
A5000 vGPU显示模式切换
随机推荐
算法面试经典100题,Android程序员最新职业规划
121. The best time to buy and sell stocks
Blue Bridge Cup microbial proliferation C language
腾讯T3大牛手把手教你,大厂内部资料
Technology sharing | packet capturing analysis TCP protocol
企业精益管理体系介绍
某东短信登录复活 安装部署教程
HDU 1026 Ignatius and the Princess I 迷宫范围内的搜索剪枝问题
理解 YOLOV1 第二篇 预测阶段 非极大值抑制(NMS)
Li Kou 101: symmetric binary tree
范式的数据库具体解释
js实现力扣71题简化路径
Learn to explore - use pseudo elements to clear the high collapse caused by floating elements
beegfs高可用模式探讨
rt-thread i2c 使用教程
【计网】第三章 数据链路层(4)局域网、以太网、无线局域网、VLAN
String长度限制?
Cesium 点击绘制圆形(动态绘制圆形)
After solving 2961 user feedback, I made such a change
[calculating emotion and thought] floor sweeper, typist, information panic and Oppenheimer