码迷,mamicode.com
首页 > Web开发 > 详细

文件上传下载

时间:2020-07-20 10:31:48      阅读:106      评论:0      收藏:0      [点我收藏+]

标签:上传下载   文件下载   ||   object   conf   远程   utf-8   codebase   dog   

报文格式

{"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());
        }
    }

文件上传下载

标签:上传下载   文件下载   ||   object   conf   远程   utf-8   codebase   dog   

原文地址:https://www.cnblogs.com/jinit/p/13343238.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!