Upload an image to Qiniu Cloud and return the image URL

When developing a project, the function of uploading pictures is often used. If all pictures are stored in the project path, the project will become more and more bloated. Therefore, you can consider uploading pictures to a third party for processing. Here we use seven Niuyun for image storage.

1. Preparations for Qiniu Cloud

1. Qiniu cloud registration and login

https://portal.qiniu.com/signup/choice
write picture description here

2. Create a new storage space

write picture description here

Enter the object storage menu, click "New storage space", here you need real-name authentication, upload the front and back of the ID card, etc., the authentication is successful in about an hour, and the efficiency is really good~

write picture description here

Remember the storage space name here, it will be used later in the code.

2. Code implementation

1. Add Qiniu cloud dependency in pom.xml

My project uses maven to manage jar packages, so just add the corresponding dependencies directly:

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

2. Add Qiniuyun picture manipulation tools

package com.cn.netdisk.util;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.Base64;
import com.qiniu.util.StringMap;
import com.qiniu.util.UrlSafeBase64;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

public class QiniuCloudUtil {

    // 设置需要操作的账号的AK和SK
    private static final String ACCESS_KEY = "你的ACCESS_KEY";
    private static final String SECRET_KEY = "你的SECRET_KEY";

    // 要上传的空间
    private static final String bucketname = "你的空间名称";

    // 密钥
    private static final Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);

    private static final String DOMAIN = "你的图片上传路径";

    private static final String style = "自定义的图片样式";

    public String getUpToken() {        
        return auth.uploadToken(bucketname, null, 3600, new StringMap().put("insertOnly", 1));
    }
    // 普通上传
    public String upload(String filePath, String fileName) throws IOException {
        // 创建上传对象
        UploadManager uploadManager = new UploadManager();
        try {
            // 调用put方法上传
            String token = auth.uploadToken(bucketname);
            if(UtilValidate.isEmpty(token)) {
                System.out.println("未获取到token,请重试!");
                return null;
            }
            Response res = uploadManager.put(filePath, fileName, token);
            // 打印返回的信息
            System.out.println(res.bodyString());
            if (res.isOK()) {
                Ret ret = res.jsonToObject(Ret.class);
                //如果不需要对图片进行样式处理,则使用以下方式即可
                //return DOMAIN + ret.key;
                return DOMAIN + ret.key + "?" + style;
            }
        } catch (QiniuException e) {
            Response r = e.response;
            // 请求失败时打印的异常的信息
            System.out.println(r.toString());
            try {
                // 响应的文本信息
                System.out.println(r.bodyString());
            } catch (QiniuException e1) {
                // ignore
            }
        }
        return null;
    }


    //base64方式上传
    public String put64image(byte[] base64, String key) throws Exception{
        String file64 = Base64.encodeToString(base64, 0);
        Integer l = base64.length;
        String url = "http://upload.qiniu.com/putb64/" + l + "/key/"+ UrlSafeBase64.encodeToString(key);      
        //非华东空间需要根据注意事项 1 修改上传域名
        RequestBody rb = RequestBody.create(null, file64);
        Request request = new Request.Builder().
                url(url).
                addHeader("Content-Type", "application/octet-stream")
                .addHeader("Authorization", "UpToken " + getUpToken())
                .post(rb).build();
        //System.out.println(request.headers());
        OkHttpClient client = new OkHttpClient();
        okhttp3.Response response = client.newCall(request).execute();
        System.out.println(response);
        //如果不需要添加图片样式,使用以下方式
        //return DOMAIN + key;
        return DOMAIN + key + "?" + style;
    }


    // 普通删除(暂未使用以下方法,未测试)
    public void delete(String key) throws IOException {
        // 实例化一个BucketManager对象
        BucketManager bucketManager = new BucketManager(auth);
        // 此处的33是去掉:http://ongsua0j7.bkt.clouddn.com/,剩下的key就是图片在七牛云的名称
        key = key.substring(33);
        try {
            // 调用delete方法移动文件
            bucketManager.delete(bucketname, key);
        } catch (QiniuException e) {
            // 捕获异常信息
            Response r = e.response;
            System.out.println(r.toString());
        }
    }

    class Ret {
        public long fsize;
        public String key;
        public String hash;
        public int width;
        public int height;
    }
}

(1). Obtain the AK and SK of the account that needs to be operated

private static final String ACCESS_KEY = "你的ACCESS_KEY";
private static final String SECRET_KEY = "你的SECRET_KEY";

Enter Personal Center - Key Management
write picture description here

(2). Get the space to upload

private static final String bucketname = "你的空间名称";

write picture description here

(3). Get the image upload URL path

private static final String DOMAIN = "你的图片上传路径";

write picture description here
(4). Get a custom picture style

private static final String style = "自定义的图片样式";

I need to add a watermark to the image here, so I customized the image style. If there is no format requirement for the uploaded image, you can skip this step.

write picture description here

You can use the processing interface of imagestyle as the value of style.

3. Back-end code call

@ResponseBody
    @RequestMapping(value="/uploadImg", method=RequestMethod.POST)
    public ResultInfo uploadImg(@RequestParam MultipartFile image, HttpServletRequest request) {
        ResultInfo result = new ResultInfo();
        if (image.isEmpty()) {
            result.setCode(400);
            result.setMsg("文件为空,请重新上传");
            return result;
        }

        try {
            byte[] bytes = image.getBytes();
            String imageName = UUID.randomUUID().toString();

            QiniuCloudUtil qiniuUtil = new QiniuCloudUtil();
            try {
                //使用base64方式上传到七牛云
                String url = qiniuUtil.put64image(bytes, imageName);
                result.setCode(200);
                result.setMsg("文件上传成功");
                result.setInfo(url);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return result;
        } catch (IOException e) {
            result.setCode(500);
            result.setMsg("文件上传发生异常!");
            return result;
        }
    }

4. Front-end code call

I am using vue, here is the image upload using the quillEditor rich text editor component, uploadImg is the method called to upload the image:

uploadImg: async function(id) {  
    var vm = this;
    var fileInput = document.getElementById("uniqueId");  
    var formData = new FormData();
    formData.append("image", fileInput.files[0]);
    this.$axios({
        method: "post",
        url: '/api/article/uploadImg',
        data: formData
    }).then((response) = >{
        if (response.data.code == 200) {
            //后端返回的url地址
            var url = response.data.info;
            if (url != null && url.length > 0) {   
                vm.addImgRange = vm.$refs.myQuillEditor.quill.getSelection();
                var index = vm.addImgRange != null ? vm.addImgRange.index: 0;   vm.$refs.myQuillEditor.quill.insertEmbed(index, 'image', url);  
            } else {
              this.$Message.error("图片添加失败!");  
            }
        } else {
            this.$Message.error(response.data.msg);
        }
    });   
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324813391&siteId=291194637