java中使用七牛云流程

文章目录

登录七牛云

新建空间
java中使用七牛云流程
java中使用七牛云流程
这里空间权限设置为公开,空间名称记好
java中使用七牛云流程
这里域名记好
java中使用七牛云流程
密钥记好

pom文件导入七牛云的maven依赖

  <!--七牛云-->
            <dependency>
                <groupId>com.qiniu</groupId>
                <artifactId>qiniu-java-sdk</artifactId>
                <version>7.2.6</version>
                <scope>compile</scope>
            </dependency>
            <dependency>
                <groupId>com.squareup.okhttp3</groupId>
                <artifactId>okhttp</artifactId>
                <version>3.3.1</version>
                <scope>compile</scope>
            </dependency>
            <dependency>
                <groupId>com.google.code.gson</groupId>
                <artifactId>gson</artifactId>
                <version>2.6.2</version>
                <scope>compile</scope>
            </dependency>
            <dependency>
                <groupId>com.qiniu</groupId>
                <artifactId>happy-dns-java</artifactId>
                <version>0.1.4</version>
                <scope>compile</scope>
            </dependency>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.12</version>
                <scope>test</scope>
            </dependency>

FileUtil工具类

主要是为了过滤上传的文件

public class FileUtil {

    // 图片允许的后缀扩展名
    public static String[] IMAGE_FILE_EXTD = new String[] { "png", "bmp", "jpg", "jpeg","pdf" };

    public static boolean isFileAllowed(String fileName) {
        for (String ext : IMAGE_FILE_EXTD) {
            if (ext.equals(fileName)) {
                return true;
            }
        }
        return false;
    }
}

QiniuService类

package com.zy.service;

import com.alibaba.fastjson.JSONObject;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.zy.utils.FileUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Service
public class QiniuService {

//    private static final Logger logger = LoggerFactory.getLogger(QiniuService.class);

    // 设置好账号的ACCESS_KEY和SECRET_KEY
    String ACCESS_KEY = "GP970";
    String SECRET_KEY = "nDoZnehWTWfVWs1tfI02H3CCOmhNBqMs";
    // 要上传的空间
    String bucketname = "lzchaohuiwan";

    // 密钥配置
    Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
    // 构造一个带指定Zone对象的配置类,不同的七云牛存储区域调用不同的zone
//    华东	Region.region0(), Region.huadong()
//    华北	Region.region1(), Region.huabei()
//    华南	Region.region2(), Region.huanan()
//    北美	Region.regionNa0(), Region.beimei()
//    东南亚	Region.regionAs0(), Region.xinjiapo()
    Configuration cfg = new Configuration(Zone.zone2());
    // ...其他参数参考类注释
    UploadManager uploadManager = new UploadManager(cfg);

    // 测试域名,只有30天有效期
    private static String QINIU_IMAGE_DOMAIN = "r3sejy2a8bkt.clouddn.com/";

    // 简单上传,使用默认策略,只需要设置上传的空间名就可以了
    public String getUpToken() {
        return auth.uploadToken(bucketname);
    }

    public String saveImage(MultipartFile file) throws IOException {
        try {
            int dotPos = file.getOriginalFilename().lastIndexOf(".");
            if (dotPos < 0) {
                return null;
            }
            String fileExt = file.getOriginalFilename().substring(dotPos + 1).toLowerCase();
            // 判断是否是合法的文件后缀
//            if (!FileUtil.isFileAllowed(fileExt)) {return null;}

           String fileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + fileExt;
            // 调用put方法上传
            Response res = uploadManager.put(file.getBytes(), fileName, getUpToken());
            // 打印返回的信息
            if (res.isOK() && res.isJson()) {
                // 返回这张存储照片的地址
                return QINIU_IMAGE_DOMAIN + JSONObject.parseObject(res.bodyString()).get("key");
            } else {
//                logger.error("七牛异常:" + res.bodyString());
                return null;
            }
        } catch (QiniuException e) {
            // 请求失败时打印的异常的信息
//            logger.error("七牛异常:" + e.getMessage());
            return null;
        }
    }
}


TestController类

package com.zy.controller;


import com.alibaba.fastjson.JSONObject;
import com.zy.service.QiniuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


@Controller
public class TestController {

    @Autowired
    private QiniuService qiniuService;

    @RequestMapping(value = "/uploadMulit", method = RequestMethod.POST)
    @ResponseBody
    public String uploadImage(@RequestParam("data") MultipartFile data, HttpServletRequest request) {

        String name = request.getParameter("name");
        System.out.println("name:"+name);
        if(data.isEmpty()) {
            return "error";
        }

        try {
            String QINIU_IMAGE_DOMAIN="r3sejy2a8kt.clouddn.com/";
            String fileUrl=qiniuService.saveImage(data);
//            fileUrl=QINIU_IMAGE_DOMAIN+fileUrl;
            return fileUrl;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "fail";
    }

    @RequestMapping("/test")
    public String test(){
        return "test";
    }
    @RequestMapping("/file")
    public String file(){
        return "file";
    }

}


上一篇:2021-07-23


下一篇:深入理解java虚拟机-垃圾收集(二)-经典垃圾收集器