WeChat applet picture upload to java background

foreword

Regarding cloud storage file upload, I really want to say a lot. This is a purely original article based on small programs or the whole process of SpringBoot's cloud storage.
The whole teaching is very detailed, suitable for all java learners, especially those who just finished learning java and want to practice their hands.



About my use and understanding of cloud storage!

Cloud storage, as the name suggests, is to store our files (here I generally refer to pictures, videos, and of course other file types) in the cloud server. In the cloud server, our pictures are compressed and saved by algorithms. in their servers and returned to us in the form of the connection address.
Here, I thought of using cloud storage because I didn't know how to deal with pictures when I was writing a professional comprehensive project. I happened to encounter this problem, and it was also the first time I came into contact with file processing that was not done through the web, so I was confused at the time, but what is certain is that I will definitely use file upload and download. At this time, I didn't directly write file upload and download. At that time, I didn't know how to upload and download files through applets, and I didn't want to store my files directly in my server, because it would waste my server space. Before this, I wrote a blog of my own. At that time, I had a lot of pictures stored in my server. The pictures were not compressed and the pictures were very large. When visiting the blog, many pictures were loaded at the same time. If there is no cache, load It's very slow, and even some of my css can't be loaded. So this doesn't make sense to me. So I had a bold idea,picture bedThe first time I came into contact with Tubed was when I was writing a blog, because there were a large number of pictures that I needed to get out of the database, so I found a method called Tubed, which is very easy to use, and it uses a connection Save my pictures in the form of , as long as you visit the address, you can get my pictures, and the front end also fits, so at first I wanted to transfer the files from the applet (front end) to the background directly through file upload and download, and then Upload the file to the picture bed website, and make a request to the picture bed website. This is an idea, I didn't go to confirm it, but I guess it is feasible, because the map bed also returns the address, at this time, I was forced to learn about cloud storage.
The essence of the picture bed is actually the same as that of cloud storage! The picture bed is the return address for uploading pictures, and so is cloud storage!

This article introduces in detail the most basic usage and implementation methods of cloud storage.


提示:以下代码仅供参考

1. What is cloud storage?

Simple understanding: it is to transfer the file to the cloud server and return it to your access address.

2. Why use cloud storage

1. My understanding

For example, if a user transfers a file to me, how do I process this file? Is it to save the file directly to the local, use the local path to store it in the database, and then display the file through its file path when the front-end needs to display it? This is feasible, but I think it is unreasonable to store the project and data on one server, which can reduce the pressure on the project server, and when using it, the pictures stored on the local server are not compressed, if the server Errors occur in the system, prone to data errors or loss, and greatly reduce the scalability of the project. At the beginning, I just felt that storing in this way was very troublesome and difficult to store when taking the files. Because I store pictures in the form of picture beds.
So there is cloud storage.

2. What is cloud storage and why should you use cloud storage? benefit?

My understanding: After I checked the information, cloud storage is actually a server storing data, and cloud storage is to put data in the cloud. Of course, after all, it is in the server of other companies, which is not absolutely safe, but for our learning and development, I think it is very good.
Here, we put large file-like data in cloud storage, which reduces the pressure on our engineering server, and cloud storage will compress the picture, put the picture in the cloud, and return it to us in the form of a picture bed.
Most importantly, it is returned to us in the form of a picture bed, which can be stored in the database in a more convenient form.
It is an online space dedicated to storing pictures and allowing you to link pictures to the outside world. It is actually a link, and you can access the link to get the picture.
For example:
http://baidu.com/6plmqdj5bcr

3. Use cloud storage

1. Create a cloud storage account

Alibaba Cloud, Tencent Cloud, and Huawei Cloud are all available. Here I will use Qiniu Cloud as an example!
Qiniu cloud registration => insert image description here
=>
After creation, you will be prompted to bind your own domain name space, which can be ignored here.
insert image description here
If you have a registered domain name, then just fill in your registered domain name. If you don’t have your own You can use your own test domain name.
insert image description here
Storage space name: unique and non-repeatable.
Storage area: optional and default.
Access control: select public

2. Upload files in the cloud storage space

Click into your own space management, click file upload, select the file you want to upload,
insert image description here
after the upload is successful,

click details
insert image description here

Visit our link address, you can open the pictures we upload!

4. How to use java to realize cloud storage function

1.token

What is a token: By requesting the cloud storage server, a base64 encrypted data is returned to you. This is the credential for java to upload files to the cloud storage space, such as your account number + password. The HTTP request here does not require us to use the RestTemplate to make the request
. Instead, Qiniu Cloud or Alibaba Cloud server provided us with an SDK (Software Development Kit) with their own http request method.

Import Qiniu Cloud SDK

		<dependency>
            <groupId>com.qiniu</groupId>
            <artifactId>qiniu-java-sdk</artifactId>
            <version>7.10.2</version>
        </dependency>

Qiniu Cloud JavaSDK documentation: https://developer.qiniu.com/linking/6279/linking-java-sdk

Use Java to obtain the token interface of Qiniu cloud storage

Learn about parameters:
accessKey secretKey bucket
accessKey secretKey Your Qiniu Cloud account key, as the only credential for you as a Qiniu Cloud user,
insert image description here
the bucket is your space name:
insert image description here

To get the token, we need to get these three parameters first, the upload process
insert image description here

Entity class:

@Data
public class QiNiu {
    
    
    private String token;
    private String key;
}

Get TOKEN

QiNiu qiNiu = new QiNiu();


    // 获取 七牛云的 token
    @RequestMapping(value = "/getToken", method = RequestMethod.GET)
    public String getToken() {
    
    
        String accessKey = "自己的accessKey";
        String secretKey = "自己的secretKey";
        String bucket = "自己的空间名";
        long expireSeconds = 600;   //过期时间
        StringMap putPolicy = new StringMap();
        //auth是七牛SDK封装的类,我们需要将我们的唯一标识符传进去
        Auth auth = Auth.create(accessKey, secretKey);
        //这里的第二个参数是key 而在请求时,内部已经有指定key了 要么这里写指定key 要么为null
        String upToken = auth.uploadToken(bucket,null,expireSeconds,putPolicy);
        qiNiu.setKey(UUID.randomUUID().toString().replaceAll("\\-", ""));
        qiNiu.setToken(upToken);
        return qiNiu.getToken();
    }

Upload to cloud storage

@GetMapping(value = "/qiniu/upload")
    public Result UpLoad(){
    
    
        Result result = new Result();
        Configuration cfg = new Configuration(Region.huanan());//Region.huanan()对应自己的存储区域 默认为region
        UploadManager uploadManager = new UploadManager(cfg);
        String token=qiNiu.getToken();
        String key=qiNiu.getKey();
        String url="";//这里是你的域名地址 测试域名或者是备案域名
        String filePath="你电脑的图片地址";
        try {
    
    
        	//这里的key 就是我们刚刚用uuid随机生成的,意味着将文件名重置,避免重复
            Response response = uploadManager.put(filePath,key,token);
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            //返回的key 就是我们的文件名
            System.out.println(putRet.hash);
            String imageUrl=url+putRet.key;
            result.setData(imageUrl);
            return result;
        } catch (QiniuException e) {
    
    
            e.printStackTrace();
            result.setMessage("err");
            return result;
        }
    }

One more thing to add here, if you pass the file from the front end, you can directly upload and download the file in the form of a stream, so that it will only be cached in your java background, and will not be stored in your server!

2. How to use the front and rear separation of the mini program to upload

flow chart

insert image description here

the code

 wx.request({
    
    
                url: 'xxxxxx/getToken',
                method: 'GET',
                header: {
    
    
                  'Content-Type': 'application/x-www-form-urlencoded',
                },
                success:function(res){
    
    
                  token = res.data;
                  wx.uploadFile({
    
    
                    url:'你空间所在对应的上传区域地址',
                    //详情地址可见官网
                    filePath: fileName,//你的文件
                    name: 'file',//文件类型
                    formData:{
    
    
                      'token':token,//java返回给你的token
                      'key':key //可以用random函数生成随机key
                    },
                    success(res) {
    
    
                        var data=res.data;//返回的hash和key
                        if(typeof data==='string')data = JSON.parse(data.trim());//解压缩
                        url= '你的测试域名或者你的备案域名' + data.key,
                        that.setData({
    
    
                          url:url
                        })
                        wx.request({
    
    
                          url: '你的图片返回请求',
                          method: 'POST',
                          header: {
    
    
                            'Content-Type': 'application/x-www-form-urlencoded',
                          },
                          data:{
    
    
                          url:url 
                          },

Summarize

Here is a reminder that if you write the wrong bucket or key value when obtaining the token, you can still return the token, but an error will occur during verification.
If you think this article is helpful to you, please give it a thumbs up!

More file upload and download File
upload and download Here is my WeChat applet open source project:
Project address: https://github.com/CaseOfShe/school
Demo address: https://www.bilibili.com/video/BV1q3411g71P

Guess you like

Origin blog.csdn.net/weixin_53690059/article/details/124761687