java后台简单从阿里云下载文件通知前端以附件的形式保存

来源:互联网 发布:仙侠世界大网络下载 编辑:程序博客网 时间:2024/05/16 11:50

java后台简单从阿里云下载文件

本文章借鉴开发文档及百度资源综合:

  • 阿里云下载文件


阿里云下载

代码块语法:

 @Override    public MessageVo getDownLoadFile(String fileName, String ossKey, HttpServletResponse response) {// fileName :前台传入的文件名(主要是标识文件是什么格式.png或.zip)// ossKey:上传文件时阿里云返回的标识// 配置阿里云基本信息 String aliyunId = ApplicationPropertyUtils.getContextProperty("ALIYUN_ACCESS_KEY_ID");              String aliyunSecret = ApplicationPropertyUtils.getContextProperty("ALIYUN_ACCESS_KEY_SECRET");              String ossEndpoint =  ApplicationPropertyUtils.getContextProperty("ALIYUN_OSS_ENDPOINT");              OSSClient ossClient  = new OSSClient(ossEndpoint, aliyunId, aliyunSecret);  // 获取fileid对应的阿里云上的文件对象              OSSObject ossObject = ossClient.getObject(bucketName, ossKey);//bucketName需要自己设置             // 已缓冲的方式从字符输入流中读取文本,缓冲各个字符,从而提供字符、数组和行的高效读取           BufferedReader reader = new BufferedReader(new    InputStreamReader(ossObject .getObjectContent()));                  // 缓冲文件输出流            BufferedOutputStream outputStream=new BufferedOutputStream(response.getOutputStream());            // 通知浏览器以附件形式下载            response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));            // 进行解码 为防止文件出现乱码 文件上传时进行编码处理            BASE64Decoder base64Decoder = new BASE64Decoder();          byte[] car;           while (true) {              String line = reader.readLine();             if (line == null) break;               car =  base64Decoder.decodeBuffer(line);                outputStream.write(car);            }          reader.close();            if(outputStream!=null){                outputStream.flush();                outputStream.close();            }        } catch (IOException e) {            e.printStackTrace();            message(" Backend file write error !!!");            return messageVo;        } catch (OssException e){          e.printStackTrace();            message(" The file name or ossKey value is error !!!");            return messageVo;        }    }

注意:在实际使用该方法下载的过程中,可能遇到服务器不报错,但就是下载不下来文件的问题,这样有可能是前端页面发出下载请求的方式有误,不能使用AJAX的get方式访问该方法,因为Ajax能够返回的数据格式只能为html,script,json,xml,不接受流的形式。笔者使用的方式是用window.location.href访问,或者使用from表单提交方式(GET/POST)。
“`
借鉴来源:
阿里云文档


阅读全文
1 0
原创粉丝点击