当前位置:网站首页>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>
边栏推荐
- 【Yann LeCun点赞B站UP主使用Minecraft制作的红石神经网络】
- 小微企业难做账?智能代账小工具快用起来
- redisson bug分析
- Chic Lang: attributeerror: partially initialized module 'CV2' has no attribute 'GAPI_ wip_ gst_ GStreamerPipe
- Tencent cloud database public cloud market ranks top 2!
- 腾讯字节等大厂面试真题汇总,网易架构师深入讲解Android开发
- Logstash expressway entrance
- Linear distance between two points of cesium
- Tencent T2 Daniel explained in person and doubled his job hopping salary
- mod_ WSGI + pymssql path SQL server seat
猜你喜欢
Li Kou 101: symmetric binary tree
腾讯字节等大厂面试真题汇总,网易架构师深入讲解Android开发
理解 YOLOV1 第二篇 预测阶段 非极大值抑制(NMS)
An East SMS login resurrection installation and deployment tutorial
Configuration and simple usage of the EXE backdoor generation tool quasar
HMS Core 机器学习服务打造同传翻译新“声”态,AI让国际交流更顺畅
Blue Bridge Cup microbial proliferation C language
MySQL information schema learning (II) -- InnoDB table
社招面试心得,2022最新Android高频精选面试题分享
Transformer model (pytorch code explanation)
随机推荐
A5000 vgpu display mode switching
爬虫(14) - Scrapy-Redis分布式爬虫(1) | 详解
学习打卡web
It's enough to read this article to analyze the principle in depth
枚举根据参数获取值
【计网】第三章 数据链路层(3)信道划分介质访问控制
js获取浏览器系统语言
MySQL information schema learning (II) -- InnoDB table
Chic Lang: attributeerror: partially initialized module 'CV2' has no attribute 'GAPI_ wip_ gst_ GStreamerPipe
POJ 3207 Ikki&#39; s Story IV – Panda&#39; s Trick (2-SAT)
Web开发小妙招:巧用ThreadLocal规避层层传值
After solving 2961 user feedback, I made such a change
Tencent Android development interview, basic knowledge of Android Development
Hudi vs Delta vs Iceberg
Teach you to learn JS prototype and prototype chain hand in hand, a tutorial that monkeys can understand
Cesium 两点之间的直线距离
语音识别(ASR)论文优选:全球最大的中英混合开源数据TALCS: An Open-Source Mandarin-English Code-Switching Corpus and a Speech
Li Kou 101: symmetric binary tree
社招面试心得,2022最新Android高频精选面试题分享
Cf960g - bandit Blues (type I Stirling number +ogf)