当前位置:网站首页>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>
边栏推荐
- Classic 100 questions of algorithm interview, the latest career planning of Android programmers
- Alibaba data source Druid visual monitoring configuration
- Color is converted to tristimulus value (r/g/b) (dry stock)
- BUUCTF---Reverse---easyre
- Node.js: express + MySQL实现注册登录,身份认证
- Guangzhou's first data security summit will open in Baiyun District
- Recursive implementation of department tree
- A5000 vgpu display mode switching
- 企业精益管理体系介绍
- Problems encountered in using RT thread component fish
猜你喜欢
Standardized QCI characteristics
Chic Lang: attributeerror: partially initialized module 'CV2' has no attribute 'GAPI_ wip_ gst_ GStreamerPipe
rt-thread i2c 使用教程
It's enough to read this article to analyze the principle in depth
5. 無線體內納米網:十大“可行嗎?”問題
A5000 vGPU显示模式切换
腾讯架构师首发,2022Android面试笔试总结
企业精益管理体系介绍
HMS Core 机器学习服务打造同传翻译新“声”态,AI让国际交流更顺畅
腾讯字节阿里小米京东大厂Offer拿到手软,老师讲的真棒
随机推荐
【计网】第三章 数据链路层(3)信道划分介质访问控制
腾讯T4架构师,android面试基础
【云小课】EI第47课 MRS离线数据分析-通过Flink作业处理OBS数据
学习打卡web
OceanBase社区版之OBD方式部署方式单机安装
力扣101题:对称二叉树
Synchronization of data create trigger synchronization table for each site
RT-Thread 组件 FinSH 使用时遇到的问题
理解 YOLOV1 第二篇 预测阶段 非极大值抑制(NMS)
Pay attention to the partners on the recruitment website of fishing! The monitoring system may have set you as "high risk of leaving"
String length limit?
Groovy基础语法整理
Chic Lang: attributeerror: partially initialized module 'CV2' has no attribute 'GAPI_ wip_ gst_ GStreamerPipe
mod_ WSGI + pymssql path SQL server seat
PHP and excel phpexcel
DOM operation
POJ3617 Best Cow Line 馋
Configuration and simple usage of the EXE backdoor generation tool quasar
Hudi vs Delta vs Iceberg
新一代垃圾回收器—ZGC