项目总结:电子签名功能-对接第三方-02-技术 -6.如何实现将OSS服务器中的文件或图片下载到本地

    //下载协议
    @RequestMapping("/download/{protocolID}")
    public void download(@PathVariable Long protocolID, HttpServletResponse response) {

        Map<String, String> map = protocolService.getDownloadUrl(protocolID);
        String downloadUrl = map.get("uploadUrl");
        String downloadFilename = map.get("protocolName");
        try {
            String encodedFileName = encodeUrlChinese(downloadFilename);
            downloadFilename = URLEncoder.encode(downloadFilename, "UTF-8");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + downloadFilename);
            BufferedOutputStream fos = new BufferedOutputStream(response.getOutputStream());

            String encodedUrl = downloadUrl.substring(0,downloadUrl.lastIndexOf("/")+1) + encodedFileName;
            URL url = new URL(encodedUrl);
            URLConnection urlCon = url.openConnection();
            urlCon.setDoOutput(false);
            InputStream fis = urlCon.getInputStream();
            byte[] buffer = new byte[1024];
            int r = 0;
            while ((r = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, r);
            }
            fis.close();
            fos.flush();
            fos.close();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    //UrlEncode编码
    private String encodeUrlChinese(String fileName){
        char[] str = fileName.toCharArray();
        StringBuilder sb = new StringBuilder();
        int strSize = fileName.length();
        char ch;
        for (int i=0,j=0; i<strSize; ++i) {
            ch = str[i];
            if (((ch>='A') && (ch<'Z')) ||
                    ((ch>='a') && (ch<'z')) ||
                    ((ch>='0') && (ch<'9'))) {
                sb.append(ch);
            } else if (ch == ' ') {
                sb.append("%20");
            } else if (ch == '.' || ch == '-' || ch == '_' || ch == '*') {
                sb.append(ch);
            } else {
                try {
                    sb.append(URLEncoder.encode(ch + "", "UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();
    }


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

追梦者晓东

我是最不起眼的程序员阿东。感谢

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

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

打赏作者

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

抵扣说明:

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

余额充值