当前位置:网站首页>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>
原网站

版权声明
本文为[£ small feather]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207061206594021.html