SpringBoot整合七牛云上传和下载功能

1、导入pom.xml依赖

 <dependencies>

       <dependency>
            <groupId>com.qiniu</groupId>
            <artifactId>qiniu-java-sdk</artifactId>
            <version>[7.7.0, 7.7.99]</version>
        </dependency>

        <!--我喜欢用fastjson所以把官方推荐的gson给注释了-->
        <!--       <dependency>
                   <groupId>com.google.code.gson</groupId>
                   <artifactId>gson</artifactId>
                   <version>2.8.5</version>
                   <scope>compile</scope>
               </dependency>-->

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.72</version>
        </dependency>


        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>


        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.4.5</version>
        </dependency>
    </dependencies>

2、上传功能

 

机房Region
华东Region.region0()Region.huadong()
华北Region.region1()Region.huabei()
华南Region.region2()Region.huanan()
北美Region.regionNa0()Region.beimei()
东南亚Region.regionAs0()Region.xinjiapo()

Region.region2() 对应的是华南地区需要你自己查看你对应的地区

   @RequestMapping("upload")
    public JSONObject upload(@RequestParam("file") MultipartFile file) throws IOException {

        JSONObject data = new JSONObject();
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.region2());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证,然后准备上传
        String accessKey = "你自己的accessKey";
        String secretKey = "你自己的secretKey";
        String bucket = "你自己的bucket";
        //如果是Windows情况下,格式是 D:\\qiniu\\test.png
        //linux服务器路径
        //String localFilePath = "/data/mop/upload";
        InputStream inputStream = file.getInputStream();
        //ByteArrayInputStream byteInputStream=new ByteArrayInputStream(inputStream);
        //默认不指定key的情况下,以文件内容的hash值作为文件名
        String key = file.getOriginalFilename();
        String path = "upload/" + key;
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);

        try {
            Response response = uploadManager.put(inputStream, path, upToken, null, null);
            //解析上传成功的结果
            //DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class); //Gson
            DefaultPutRet putRet = JSONObject.parseObject(response.bodyString(), DefaultPutRet.class);//fastJson   
            data.put("url", "你的域名" + path);
            //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
            }
        }
        return data;
    }

3、下载功能

 /**
     * 通过流的方式浏览器进行下载
     *
     * @param fileName 需要下载的文件名
     * @param url 需要下载文件的url 也是上面上传之后返回给你的url
     * @param res
     * @throws Exception
     */
    @RequestMapping("download")
    public void download(String fileName, String url, HttpServletResponse res) throws IOException {
        InputStream inputStream = null;
        OutputStream os = null;
        try {
//            if (StringUtils.isEmpty(fileName)) {
//                fileName = "ExcelServiceImplTest.java";
//            }
            //二选一都可用
            inputStream = HttpRequest.get(url).execute().bodyStream();
            // inputStream = new URL(url).openStream();
            
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            inputStream.close();

            byte[] data = outStream.toByteArray();
            res.reset();
            res.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            res.setContentType("application/octet-stream");
            os = res.getOutputStream();
            os.write(data);
            os.flush();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
            if (os != null) {
                os.close();
            }
        }
    }



    /**
     * 通过hutool工具类直接下载到本地
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        String url = "url";
        HttpUtil.downloadFileFromUrl(url, "D:\\qiniuyun");

    }

posted @ 2021-08-26 11:28  难忘是想起  阅读(0)  评论(0)    收藏  举报  来源