zoukankan      html  css  js  c++  java
  • 文件上传下载

    报文格式

    {"name":"文件名","out":"文件字节码"}
    

    通过接口下载远程文件

     public void downloadFrom(HttpServletResponse res, HttpServletRequest request, Integer id) throws IOException{
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("fileId",id);
            String urls = ConfigUtils.getProp("online.industrial.download.urls");
    
            String doGet = HttpClientUtils.doGet(urls+"?fileId="+id);
            System.out.println(doGet);
            Map<String, Object> parseObject = JSON.parseObject(doGet, Map.class);
    
            String object = (String) parseObject.get("out");
            //用base64进行解码
            byte[] decodeByte = Base64.decodeBase64(object);
            //将解码的二进制文件转换为inputStream
            InputStream is = new ByteArrayInputStream(decodeByte);
            String name = parseObject.get("name").toString();
            String userAgent = request.getHeader("User-Agent");
            //针对IE或者以IE为内核的浏览器
            if (userAgent.contains("MSIE")||userAgent.contains("Trident")) {
                name = java.net.URLEncoder.encode(name, "UTF-8");
            } else {
                //非IE浏览器的处理:
                name = new String(name.getBytes("UTF-8"),"ISO-8859-1");
            }
            res.setContentType("application/octet-stream;charset=UTF-8");
            res.setHeader("Content-disposition", String.format("attachment; filename="%s"", name));
            OutputStream fout = res.getOutputStream();
            int len = 0;
            try {
                byte[] b = new byte[1024];
                while ((len = is.read(b)) > 0) {
                    fout.write(b, 0, len);
                }
                fout.flush();
                fout.close();
            } catch (Exception e) {
                e.getMessage();
            }
        }
    

    提供下载接口

     @RequestMapping(value = "/get/download/to")
        @ResponseBody
        public String downFile(HttpServletRequest request, HttpServletResponse response,Integer id) {
            Map<String, Object> m = new HashMap<String, Object>();
            try {
                logger.info("文件下载参数:id=[{}]", id);
                YdAttachment ydAttachment=iAttachmentService.downloadAttachmentToYd(id);
                String name =String.valueOf(ydAttachment.getFileName());
                //使用base64进行编码
                logger.info("content:{}",ydAttachment.getContent());
                //获取数据库字节码ydAttachment.getContent();若为文件则需要将文件转化为字节码输出流,并以字节码数组形式
                m.put("out", new BASE64Encoder().encode(ydAttachment.getContent()));
                logger.info("fileByte:{}",m.get("out"));
                m.put("name",name);
            } catch (Exception e) {
                logger.info("文件下载出现异常:" + e.toString());
            }
            return JSON.toJSONString(m);
        }
    

    根据远程接口下载文件

    @RequestMapping(value = "/get/download/from")
        @ResponseBody
        public void test(HttpServletRequest request, HttpServletResponse response, int fileId){
            try {
                String doGet = HttpClientUtils.doGet("http://localhost:18080/get/download/file?id="+fileId);
                //转换为json格式字符串并去除BASE64编码产生的\r\n字符
               String jsonStr = doGet.replace("\"", """)
                        .replace(""{", "{")
                        .replace("}"", "}")
                        .replace("\\r\\n","");
                logger.info("doGet:{}",doGet);
                logger.info("jsonStr:{}",jsonStr);
                Map<String, Object> parseObject = JSON.parseObject(jsonStr, Map.class);
                String filebytes = (String) parseObject.get("out");
                //用BASE64进行解码
                byte[] decodeByte = new BASE64Decoder().decodeBuffer(filebytes);
                logger.info("decodeByte:{}", decodeByte);
                //将解码的二进制文件转换为inputStream
                InputStream is = new ByteArrayInputStream(decodeByte);
                String name = parseObject.get("name").toString();
                String userAgent = request.getHeader("User-Agent");
                //针对IE或者以IE为内核的浏览器
                if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
                    name = java.net.URLEncoder.encode(name, "UTF-8");
                } else {
                    //非IE浏览器的处理:
                    name = new String(name.getBytes("UTF-8"), "ISO-8859-1");
                }
                response.setContentType("application/octet-stream;charset=UTF-8");
                response.setHeader("Content-disposition", String.format("attachment; filename="%s"", name));
                OutputStream fout = response.getOutputStream();
                int len;
                byte[] b = new byte[1024];
                try {
                    while ((len = is.read(b)) > -1) {
                        fout.write(b, 0, len);
                    }
                    fout.flush();
                } catch (Exception e) {
                    e.getMessage();
                } finally {
                    fout.close();
                }
            } catch (Exception e) {
                logger.info("文件下载出现异常:" + e.toString());
            }
        }
    
  • 相关阅读:
    前置机器学习(一):数学符号及希腊字母
    大神造轮子与小白调包侠#0509
    Windows下的apache maven安装与配置
    Windows下的apache tomcat安装与配置
    C++ <Algorithm>小小总结
    Markdown 小记
    http状态码
    vim命令
    C++ inline
    爬虫前提——正则表达式语法以及在Python中的使用
  • 原文地址:https://www.cnblogs.com/jinit/p/13343238.html
Copyright © 2011-2022 走看看