当前位置:网站首页>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>边栏推荐
- Test Li hi
- Tencent architects first, 2022 Android interview written examination summary
- Crawler (14) - scrape redis distributed crawler (1) | detailed explanation
- Leetcode 30. Concatenate substrings of all words
- Synchronization of data create trigger synchronization table for each site
- Tips for web development: skillfully use ThreadLocal to avoid layer by layer value transmission
- How to handle the timeout of golang
- Problems encountered in using RT thread component fish
- MySQL information schema learning (II) -- InnoDB table
- Tencent cloud database public cloud market ranks top 2!
猜你喜欢

In simple terms, interview surprise Edition

Example of shutter text component

After solving 2961 user feedback, I made such a change

《数字经济全景白皮书》保险数字化篇 重磅发布

A5000 vGPU显示模式切换

系统与应用监控的思路和方法

Standardized QCI characteristics

VMware virtual machine cannot open the kernel device "\.\global\vmx86"

An East SMS login resurrection installation and deployment tutorial

Oceanbase Community Edition OBD mode deployment mode stand-alone installation
随机推荐
[infrastructure] deployment and configuration of Flink / Flink CDC (MySQL / es)
121. 买卖股票的最佳时机
Wonderful coding [hexadecimal conversion]
POJ 3207 Ikki&#39; s Story IV – Panda&#39; s Trick (2-SAT)
MySql必知必会学习
Li Kou 101: symmetric binary tree
350. 两个数组的交集 II
从sparse.csc.csr_matrix生成邻接矩阵
【GET-4】
语音识别(ASR)论文优选:全球最大的中英混合开源数据TALCS: An Open-Source Mandarin-English Code-Switching Corpus and a Speech
Information System Project Manager - Chapter VIII project quality management
In simple terms, interview surprise Edition
【云小课】EI第47课 MRS离线数据分析-通过Flink作业处理OBS数据
2022年6月语音合成(TTS)和语音识别(ASR)论文月报
Groovy基础语法整理
Period compression filter
Crawler (14) - scrape redis distributed crawler (1) | detailed explanation
Tencent T3 Daniel will teach you hand-in-hand, the internal information of the factory
手把手教你学会js的原型与原型链,猴子都能看懂的教程
PHP与EXCEL PHPExcel