Base64下载图片|视频|pdf等(浏览器直接下载)

@GetMapping("/t8")
    public void down2(HttpServletResponse response) throws Exception {
        response.reset();
        response.setContentType("application/octet-stream;charset=utf-8");
        response.setHeader(
                "Content-disposition",
                "attachment; filename=222.mp4");
        Base64.Decoder DECODER_64 = Base64.getDecoder();
        //存照片
        String s = Base64Utils.fileToBase64Str(new File("C:\\Users\\Harbor\\Pictures\\Camera Roll\\222.mp4"));
        byte[] bytes =  DECODER_64.decode(s);
        try(
                // 输出流
                BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
        ){
                bos.write(bytes);
        }
    }

    public static void main(String[] args) {
        File file = new File("C:\\Users\\Harbor\\Pictures\\Camera Roll\\222.mp4");
        System.out.println(file.getName());
        System.out.println(file.getParent());
        System.out.println(file.getParentFile());
    }

工具类

package com.atguigu.yygh.cmn.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;

import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import java.util.Base64;

public class Base64Utils {

    // Base64 编码与解码
    private static final Base64.Decoder DECODER_64 = Base64.getDecoder();
    private static final Base64.Encoder ENCODER_64 = Base64.getEncoder();

    // dpi越大转换后的图片越清晰,相对转换速度越慢
    private static final Integer DPI = 200;

    // 编码、解码格式
    private static final String CODE_FORMATE = "UTF-8";

    /**
     * 1. text明文 转 Base64字符串
     * @param text  明文
     * @return      Base64 字符串
     */
    public static String textToBase64Str(String text) {
        if (StringUtils.isBlank(text)) {
            return text;
        }
        String encodedToStr = null;
        try {
            encodedToStr = ENCODER_64.encodeToString(text.getBytes(CODE_FORMATE));
        } catch (UnsupportedEncodingException e) {
            e.getMessage();
        }
        return encodedToStr;
    }

    /**
     * 2. text的Base64字符串 转 明文
     * @param base64Str text的Base64字符串
     * @return          text明文
     */
    public static String base64StrToText(String base64Str) {
        if (StringUtils.isBlank(base64Str)) {
            return base64Str;
        }
        String byteToText = null;
        try {
            byteToText = new String(DECODER_64.decode(base64Str), CODE_FORMATE);
        } catch (UnsupportedEncodingException e) {
            e.getMessage();
        }
        return byteToText;
    }

    /**
     * 3. 文件(图片、pdf) 转 Base64字符串
     * @param file  需要转Base64的文件
     * @return      Base64 字符串
     */
    public static String fileToBase64Str(File file) throws IOException {
        String base64Str = null;
        FileInputStream fin = null;
        BufferedInputStream bin = null;
        ByteArrayOutputStream baos = null;
        BufferedOutputStream bout = null;
        try {
            fin = new FileInputStream(file);
            bin = new BufferedInputStream(fin);
            baos = new ByteArrayOutputStream();
            bout = new BufferedOutputStream(baos);
            // io
            byte[] buffer = new byte[1024];
            int len = bin.read(buffer);
            while(len != -1){
                bout.write(buffer, 0, len);
                len = bin.read(buffer);
            }
            // 刷新此输出流,强制写出所有缓冲的输出字节
            bout.flush();
            byte[] bytes = baos.toByteArray();
            // Base64字符编码
            base64Str = ENCODER_64.encodeToString(bytes).trim();
        } catch (IOException e) {
            e.getMessage();
        } finally{
            try {
                fin.close();
                bin.close();
                bout.close();
            } catch (IOException e) {
                e.getMessage();
            }
        }
        return base64Str;
    }

    /**
     * 4. Base64字符串 转 文件(图片、pdf) -- 多用于测试
     * @param base64Content Base64 字符串
     * @param filePath      存放路径
     */
    public static void base64ContentToFile(String base64Content, String filePath) throws IOException{
        BufferedInputStream bis = null;
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;
        try {
            // Base64解码到字符数组
            byte[] bytes =  DECODER_64.decode(base64Content);
            ByteArrayInputStream byteInputStream = new ByteArrayInputStream(bytes);
            bis = new BufferedInputStream(byteInputStream);
            File file = new File(filePath);
            File path = file.getParentFile();
            if(!path.exists()){
                path.mkdirs();
            }
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            // io
            byte[] buffer = new byte[1024];
            int length = bis.read(buffer);
            while(length != -1){
                bos.write(buffer, 0, length);
                length = bis.read(buffer);
            }
            // 刷新此输出流,强制写出所有缓冲的输出字节
            bos.flush();
        } catch (IOException e) {
            e.getMessage();
        }finally{
            try {
                bis.close();
                fos.close();
                bos.close();
            } catch (IOException e) {
                e.getMessage();
            }
        }
    }




    // 测试
    public static void main(String args[]) throws IOException {
        // 1.测试:text明文 转 Base64字符串
        String s = fileToBase64Str(new File("C:\\Users\\Harbor\\Pictures\\Camera Roll\\111.jpg"));
        System.out.println(s);
        base64ContentToFile(s,"C:\\Users\\Harbor\\Pictures\\Camera Roll\\232.jpg");

    }
}

相关推荐

  1. uniapp微信小程序下载base64图片流或https图片

    2024-04-12 07:24:04       41 阅读
  2. uniapp微信小程序下载保存图片流到本地,base64

    2024-04-12 07:24:04       48 阅读
  3. 微信小程序下载 base64 视频文件到本地相册

    2024-04-12 07:24:04       44 阅读
  4. base64PDF

    2024-04-12 07:24:04       38 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-04-12 07:24:04       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-12 07:24:04       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-12 07:24:04       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-12 07:24:04       20 阅读

热门阅读

  1. kafka enable.auto.commit和auto.offset.reset使用说明

    2024-04-12 07:24:04       18 阅读
  2. H5如何中断已经发出去的网络请求

    2024-04-12 07:24:04       14 阅读
  3. C++中,与类型转换相关的四个关键字

    2024-04-12 07:24:04       13 阅读
  4. 嵌入式软件裸机开发--循环-查询架构

    2024-04-12 07:24:04       14 阅读
  5. 自动驾驶感知场景挖掘

    2024-04-12 07:24:04       15 阅读
  6. LiveData和ViewModel源码学习

    2024-04-12 07:24:04       15 阅读
  7. * ./cptable in ./node_modules/xlsx-style/dist/cpexcel.js

    2024-04-12 07:24:04       14 阅读
  8. Android中的drawable

    2024-04-12 07:24:04       12 阅读
  9. DA转换(数模转换)

    2024-04-12 07:24:04       14 阅读
  10. 18. 【Android教程】图片控件 ImageView

    2024-04-12 07:24:04       14 阅读