后端七牛云上传图片流程以及后续异常javax.net.ssl.SSLHandshakeException处理

4 篇文章 0 订阅

一.sprinboot整合七牛云

1.先导入依赖

<dependency>
    <groupId>com.qiniu</groupId>
    <artifactId>qiniu-java-sdk</artifactId>
    <version>[7.7.0, 7.10.99]</version>
</dependency>
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.5</version>
    <scope>compile</scope>
</dependency>
<dependency>
    <groupId>com.qiniu</groupId>
    <artifactId>happy-dns-java</artifactId>
    <version>0.1.6</version>
    <scope>test</scope>
</dependency>

2.工具类
ImageUtils

/**
 * 图片上传工具类
 */
@Component
public class ImageUtils {


    @Value("${qiniu.accessKey}")
    private  String accessKey;      //公钥
    @Value("${qiniu.secretKey}")
    private  String accessSecretKey;   //私钥
    @Value("${qiniu.bucketName}")
    private  String bucket;   // 存储空间
    @Value("${qiniu.imageUrl}")
    private String url;

    /**
     * 处理多文件
     * @param multipartFiles
     * @return
     */
    public Map<String, List<String>> uploadImages(MultipartFile[] multipartFiles){
        Map<String, List<String>> map = new HashMap<>();
        List<String> imageUrls = new ArrayList<>();
        /**
         * for循环实现存储多个
         */
        for(MultipartFile file : multipartFiles){
            imageUrls.add(uploadImageQiniu(file));
        }
        /**
         * 返回map 里面存储图片链接
         */
        map.put("imageUrl",imageUrls);
        return map;
    }

    /**
     * 上传图片到七牛云
     * @param multipartFile
     * @return
     */
    private String uploadImageQiniu(MultipartFile multipartFile){
        try {

            //1、获取文件上传的流
            byte[] fileBytes = multipartFile.getBytes();
            //2、创建日期目录分隔
//            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
//            String datePath = dateFormat.format(new Date());
            //时间格式化格式
            /**
             * 现在改用当前时间戳
             */
            SimpleDateFormat simpleDateFormat =new SimpleDateFormat("yyyyMMddHHmmssSSS");
            //获取当前时间并作为时间戳给文件夹命名
            String timeStamp1=simpleDateFormat.format(new Date());

            //3、获取文件名
            String originalFilename = multipartFile.getOriginalFilename();

            /**
             * String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
             * 原来是uuid然后使用这个
             * 加前后追String filename = datePath+"/"+ UUID.randomUUID().toString().replace("-", "")+ suffix;
             */
            String filename=   Md5Util.getMd5(originalFilename)+timeStamp1;

            //4.构造一个带指定 Region 对象的配置类
            //Region.南(根据自己的对象空间的地址选
            Configuration cfg = new Configuration(Region.xinjiapo());//这是七牛云相关配置类上传的东西协议配置需要经行修改

 
            UploadManager uploadManager = new UploadManager(cfg);

            //5.获取七牛云提供的 token
            Auth auth = Auth.create(accessKey, accessSecretKey);
            String upToken = auth.uploadToken(bucket);

            uploadManager.put(fileBytes,filename,upToken);
//这里问题出现在七牛云路径和文件名之间是有"/"的
            return url+"/"+filename;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

3.application.yaml配置

   #上传大小限制为4mb总上传大小不限制
  servlet:
    multipart:
      max-file-size: 5MB
      max-request-size: -1



#七牛云配置


qiniu:
  # 公钥
  accessKey: ############
  # 私钥
  secretKey: ############
  # 存储空间名
  bucketName: ############
  # 域名/路径
  imageUrl: ############```

4.前台vue 发送的请求

<!--图片上传部分-->
      <el-upload
          style="width: border-box"
          class="upload-demo"
          :action="this.action"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :file-list="multipartFile"
          list-type="picture"><!--multipartFile 是装载你的图片文件数组,this.action是后端接口地址restful风格,在vue data	return里面申明-->
        <el-button size="small" type="primary" >上传</el-button>
        <br>
        <div slot="tip" class="el-upload__tip">(不超过4Mb的jpg/png文件 上传成功后请刷新游览器)</div>
      </el-upload>
        </div>
<el-form-item>
  <el-button   type="primary" @click="submitForm('ruleForm')">确认修改</el-button>
  &nbsp;&nbsp;&nbsp;
  <el-button @click="resetForm('ruleForm')">重置</el-button>

5.controller的处理

 @Autowired
    private ImageUtils imageUtils;
    @CrossOrigin
    @PostMapping("/image/upload/{id}")
    public void uploadImage(@RequestParam(value = "file",required = false) MultipartFile[] multipartFile,@PathVariable("id") int id) throws Exception{

        /**
         * 七牛云上传接口
         * 传入文件数组 进入工具类 返回一个链接
         *   用restful风格在上传的图片的时候 获取id
         *   调用封装好的上传工具类后用id 调用 update更改链接
         * 页面写俩个就好
         *
         */
//      需要添加的外链接
        if (id!=0) {
            //新建实体类
            TRecruitmentAticle tr = new TRecruitmentAticle();
            //绑定对应记录
            tr.setId(id);
            if (multipartFile != null) {
                    //上传操作
                Map<String, List<String>> uploadImagesUrl = imageUtils.uploadImages(multipartFile);
                /**
                 * 外链接组
                 */
                List<String> urls = uploadImagesUrl.get("imageUrl");
                //读取存储的单挑或者多条是数据 逗号间隔
                for (int i = 0; i < urls.size(); i++) {
                    String url="";
                    if (urls.size()==1){
                        url=urls.get(0);
                    }
                    else{
                        url+=urls.get(i)+",";
                    }
                    tr.setImgUrl(url);
                }

                tRecruitmentAticleService.updateById(tr);
            }
        }
    }

二.异常处理

最先使用的是七牛云官方默认配制的域名所有安全机制都是给我们弄好的, 所以后期项目改变域名的时候就容易出现错误
我这次出现的就是异常

  javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target on  你的接口路径 ip:端口

为此我查了很多,最后才发现我sb了,因为没在七牛云配置传输方式,申请域名过后内配置https,而之前默认使用https ,所以需要警用
代码如下


```java
/**
 * 图片上传工具类
 */
@Component
public class ImageUtils {


    @Value("${qiniu.accessKey}")
    private  String accessKey;      //公钥
    @Value("${qiniu.secretKey}")
    private  String accessSecretKey;   //私钥
    @Value("${qiniu.bucketName}")
    private  String bucket;   // 存储空间
    @Value("${qiniu.imageUrl}")
    private String url;

    /**
     * 处理多文件
     * @param multipartFiles
     * @return
     */
    public Map<String, List<String>> uploadImages(MultipartFile[] multipartFiles){
        Map<String, List<String>> map = new HashMap<>();
        List<String> imageUrls = new ArrayList<>();
        /**
         * for循环实现存储多个
         */
        for(MultipartFile file : multipartFiles){
            imageUrls.add(uploadImageQiniu(file));
        }
        /**
         * 返回map 里面存储图片链接
         */
        map.put("imageUrl",imageUrls);
        return map;
    }

    /**
     * 上传图片到七牛云
     * @param multipartFile
     * @return
     */
    private String uploadImageQiniu(MultipartFile multipartFile){
        try {

            //1、获取文件上传的流
            byte[] fileBytes = multipartFile.getBytes();
            //2、创建日期目录分隔
//            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
//            String datePath = dateFormat.format(new Date());
            //时间格式化格式
            /**
             * 现在改用当前时间戳
             */
            SimpleDateFormat simpleDateFormat =new SimpleDateFormat("yyyyMMddHHmmssSSS");
            //获取当前时间并作为时间戳给文件夹命名
            String timeStamp1=simpleDateFormat.format(new Date());

            //3、获取文件名
            String originalFilename = multipartFile.getOriginalFilename();

            /**
             * String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
             * 原来是uuid然后使用这个
             * 加前后追String filename = datePath+"/"+ UUID.randomUUID().toString().replace("-", "")+ suffix;
             */
            String filename=   Md5Util.getMd5(originalFilename)+timeStamp1;

            //4.构造一个带指定 Region 对象的配置类
            //Region.南(根据自己的对象空间的地址选
            Configuration cfg = new Configuration(Region.xinjiapo());//这是七牛云相关配置类上传的东西协议配置需要经行修改

            /**
             *我的问题所在
             * 域名不支持hhtps访问,所以会出现ssl验证错误,改用http传输问题解决
             */
            cfg.useHttpsDomains = false;
            UploadManager uploadManager = new UploadManager(cfg);

            //5.获取七牛云提供的 token
            Auth auth = Auth.create(accessKey, accessSecretKey);
            String upToken = auth.uploadToken(bucket);

            uploadManager.put(fileBytes,filename,upToken);
//这里问题出现在七牛云路径和文件名之间是有"/"的
            return url+"/"+filename;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
这次问题就暂时解决了 后续出现问题也将会放在本文

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
在 Node.js 中使用七牛云实现图片下载可以按照以下步骤进行: 1. 首先,保你已经安装了 `qiniu` 模块,可以通过以下命令进行安装: ``` npm install qiniu ``` 2. 在你的代码中引入 `qiniu` 模块: ```javascript const qiniu = require('qiniu'); ``` 3. 设置七牛云的相关配置,包括 Access Key、Secret Key 和存储空间的名称: ```javascript const accessKey = 'your-access-key'; const secretKey = 'your-secret-key'; const bucket = 'your-bucket-name'; ``` 4. 初始化七牛云的配置: ```javascript const mac = new qiniu.auth.digest.Mac(accessKey, secretKey); const config = new qiniu.conf.Config(); const bucketManager = new qiniu.rs.BucketManager(mac, config); ``` 5. 定义一个函数来下载图片图片的 key(文件名)作为参数: ```javascript function downloadImage(key) { return new Promise((resolve, reject) => { const savePath = './images/' + key; // 设置保存图片的路径和文件名 const options = { force: true, // 强制覆盖已存在的文件 }; bucketManager.fetch(bucket, key, savePath, options, (err, respBody, respInfo) => { if (err) { reject(err); } else { resolve(respInfo); } }); }); } ``` 6. 调用 `downloadImage` 函数来下载图片图片的 key: ```javascript downloadImage('your-image-key') .then(respInfo => { console.log('图片下载成功', respInfo); }) .catch(err => { console.error('图片下载失败', err); }); ``` 以上代码会将指定的图片下载到当前目录下的 `./images/` 文件夹中,并输出相应的结果信息。 请注意替换代码中的 `your-access-key`、`your-secret-key` 和 `your-bucket-name` 为你自己的七牛云的相关信息,以及将 `'your-image-key'` 替换为你要下载的图片的实际 key。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝胖子不是胖子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值