zoukankan      html  css  js  c++  java
  • 文件下载转码处理类

    import org.apache.commons.codec.binary.Base64;
    import javax.servlet.http.HttpServletResponse;
    import java.io.*;
    import java.net.HttpURLConnection;
    import java.net.URL;
    
    
    //1.文件下载(postman可试)
    public static void postmanLoad(String url, HttpServletResponse response) throws Exception {
    
            File file = new File(url);
    
            byte [] bytes = File2byte(file);
            try {
    
                response.setHeader("Content-Disposition",
                        "attachment; filename="" + "123.jpg" + """);
                OutputStream out = response.getOutputStream();
                if (bytes != null) {
                    out.write(bytes);
                }
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    /** * 将文件转换成byte数组 */ public static byte[] File2byte(File tradeFile){ byte[] buffer = null; try { FileInputStream fis = new FileInputStream(tradeFile); ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] b = new byte[10240]; int n; while ((n = fis.read(b)) != -1) { bos.write(b, 0, n); } fis.close(); bos.close(); buffer = bos.toByteArray(); }catch (FileNotFoundException e){ e.printStackTrace(); }catch (IOException e){ e.printStackTrace(); } return buffer; }
    //2.从地址下载转成Base64编码 public static String downLoadFromUrlBase64(String urlStr) throws Exception { URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); //设置超时间为10秒 conn.setConnectTimeout(10 * 1000); //得到输入流 InputStream inputStream = conn.getInputStream(); return DownLoadFileUtil.getBase64FromInputStream(inputStream); } /** * 将inputstream转为Base64 public static String getBase64FromInputStream(InputStream is) throws Exception { // 将图片文件转化为字节数组字符串,并对其进行Base64编码处理 byte[] data = null; // 读取图片字节数组 try { ByteArrayOutputStream swapStream = new ByteArrayOutputStream(); byte[] buff = new byte[100]; int rc = 0; while ((rc = is.read(buff, 0, 100)) > 0) { swapStream.write(buff, 0, rc); } data = swapStream.toByteArray(); } catch (IOException e) { e.printStackTrace(); } finally { if (is != null) { try { is.close(); } catch (IOException e) { throw new Exception("输入流关闭异常"); } } } return Base64.encodeBase64String(data); }
  • 相关阅读:
    理解dajngo ORM查询中select_related的作用
    Django 模型层 Meta 选项详解
    token和session的区别
    Python 爬虫 urllib、urllib2、urllib3用法及区别
    linux里面访问一个链接的方法
    scrapy-redis实现全站分布式数据爬取
    linux shell 操作 mysql命令(不进入mysql操作界面)
    后台+下载(wget)+多个下载url
    维基下载页面说明(指南)
    pytorch --Rnn语言模型(LSTM,BiLSTM) -- 《Recurrent neural network based language model》
  • 原文地址:https://www.cnblogs.com/lifan12589/p/15108103.html
Copyright © 2011-2022 走看看