java:文件转base64,支持图片和doc/csv/pdf等常用文件

最近项目搭建了服务器集群,然后在解决文件的远程上传下载,查看,不想用ftp,想用http来搞,这就涉及到文件的传输问题,转base64挺不错。

本地的话直接用IO流就可以了,因为集群后不能保证文件一定在客户当时进入的那台保存会有一些问题,只能搞远程。

直接上代码了:FileConvertBase64

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Encoder;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
*@Description 文件转base64
*/
    public class FileConvertBase64 {
    Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     *  参数为照片的目录路径+文件名称+文件后缀
     * @param imgFile
     * @return
     */
    public String GetFileStr(String imgFile) {//将文件转化为字节数组字符串,并对其进行Base64编码处理
        InputStream in = null;
        byte[] data = null;
       //读取文件字节数组
        try {
            in = new FileInputStream(imgFile);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);//返回Base64编码过的字节数组字符串
    }

    public static void main(String[] args) {
        String base64Str = null;
        try {
            FileConvertBase64 p = new FileConvertBase64();
            String  fileName="D:\\data\\static\\123.docx";
            base64Str = p.GetFileStr(fileName);
            System.out.println(base64Str);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

经本人测试 图片、word、excel、等文件可以

注意点:

如果有人需要将word等比较大的base64再次转成byte[]的话,可能报错base64非法异常问题,问题不是因为转换的base64有问题,而是其转换方法问题,如常用的decode()方法,会因为文件过大报错,解决办法就是:

	//base64字符串转成byte[]
    public static byte[] decodeFromString(String src) {
        return src.isEmpty() ? new byte[0] : getMimeDecoder().decode(src.getBytes(DEFAULT_CHARSET));
    }

可以参考我下面的demo

import com.example.demo2.utils.FileConvertBase64;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import static java.util.Base64.getMimeDecoder;


public class demo {
    private final static Charset DEFAULT_CHARSET;

    static {
        DEFAULT_CHARSET = StandardCharsets.UTF_8;
    }
    public static void main(String[] args) {
      /* String base64Data="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQQAAAEECAIAAABBat1dAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAABcRAAAXEQHKJvM/AAAp60lEQVR42u3deZxdZX0/8O/3Wc5yl1kyk2SSkIWQBAgCYZdNo+CK+HKBn7gUtGq1WrX0p1bbX1t/2trFKm649Fcq1lKXKrhURARBCgIKJrIvISSEbJNktnvvueecZ/n+/pjDYpRx7tx7ZxL9vl/+Izn3LM+9n3nOc57lIBEBYwxAzPUJMHag4DAwVuAwMFbgMDBW4DAwVuAwMFbgMDBWUM/0D4g4O2ewX0dH94479YFa6m9p6SRbusAD5CS7Z+ormqtf3SSuGRgrcBgYK3AYGCtwGBgrqGlud8kll6xbt679423cuPHiiy+e/vbtNOxaaqq2s6up99xOo7Cdy2+pLd7B1nYHG8Gz/KubbhjWrVu3fv36Tl0kY9Mxy786vk1irMBhYKzAYWCsMMMwYCtuvPHGGZ/ffrtq6TToV0298dR73m9X+2089YGoFd0rnJb23M5JtnNFLV1vx391XDMwVuAwMFbgMDBW4DAwVphup9usmbpntKWG4Fz1QE/92Q52/XZwcHgHr6ilSzigcM3AWIHDwFiBw8BYgcPAWOGAa0BPrZ1Wb/fmInewWd/OFXXw2UP3zupAxjUDYwUOA2MFDgNjBQ4DY4UZNqBvuOGG6W+8du3a6W/cvUWm2umQbqeTtYMLgXWw93rqz3Zwzx1sQHfvVzdphmHg+dBs9nX7V8e3SYwVOAyMFaZ7m7Rx48aOHK9T+2G/D2b5V4fP1L45QFbh5n/9ff7X7uFVuBmbCoeBsQKHgbECh4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jBQ4DY4Xpvge6e1qa9Dz1Z1s6UPeut6VdtTPA+wB5XdisNdxb2pjnQDM2cxwGxgocBsYKHAbGCtOdA33JJZesW7eu/eNt3Ljx4osvnv72HRwc3sEm8ly9mGvqK+revO3uXX47pdHxHujphmHdunXr16/v7LEZO6DwbRJjBQ4DYwUOA2OFriwitp8bbrhh+u2NdjpZD4rloLs323jWpq3PVW99S7uaQSufawbGChwGxgocBsYKHAbGCp15jdUBooPLk3XvuO3satauqB3dm9bc7ZHkXDMwVuAwMFbgMDBW4DAwVvidakC300HbwQm1HXxZdUsn2Y4Ojtnu3uOEbq8rzjUDYwUOA2MFDgNjBQ4DY4UZNqBvuOGG6W+8du3a6W/cvTdiTf3Zlt4iPGuvz+re+6e798DgAFnPfAYlOcMw8Hxo9ruHb5MYK3AYGCtM9zZp48aNHTlep/bDWMd15j3Q7ThARvzO1dupZ3mh6ZmVVUuXMFdLdrdzzpP4NomxAoeBsQKHgbECh4GxwgH3HmjG5grXDIwVOAyMFTgMjBU4DIwVOAyMFTgMjBX+P1FShfvkU7WKAAAAAElFTkSuQmCC";
        String[] d = base64Data.split("base64,");
        String data = d[1];
        String dataPrix=d[0];*/

        String data = null;
        try {
            FileConvertBase64 p = new FileConvertBase64();
            String  fileName="D:\\data\\static\\Judge.csv";   //图片肯定是没问题的,我们这里用csv文件测试
            data = p.GetFileStr(fileName);
            System.out.println(data);
        } catch (Exception e) {
            e.printStackTrace();
        }

        String filePath="D:/data/static/";
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); // 设置日期格式
        String dateUrl = df.format(new Date()); // new Date() 为获取当前系统时间

        String FileName="";
        UUID uuid2 = UUID.randomUUID();
        String s = String.valueOf(uuid2);
        String replace = s.replace("-", "");
        FileName = replace + ".csv";
        String tempFileName = dateUrl + "/" + FileName;

        byte[] bs = decodeFromString(data);
        try {
            FileUtils.writeByteArrayToFile(new File(filePath, tempFileName), bs);
        } catch (IOException e) {
            System.out.println("写入文件出错");
        }


    }
    public static byte[] decodeFromString(String src) {
        return src.isEmpty() ? new byte[0] : getMimeDecoder().decode(src.getBytes(DEFAULT_CHARSET));
    }
}
展开阅读全文

java后台将base64字符串换为PDF后生成的PDF打不开怎么回事呀

10-12
![图片说明](https://img-ask.csdn.net/upload/201910/12/1570868633_161609.jpg) 后台代码: public static void base64StringToPdf(String base64Content,String filePath){ File file = new File(filePath);// 将原来参数修改为字符串 BASE64Decoder decoder = new BASE64Decoder(); BufferedInputStream bin = null; FileOutputStream fout = null; BufferedOutputStream bout = null; try { //将base64编码的字符串解码成字节数组 byte[] bytes = decoder.decodeBuffer(base64Content); //创建一个将bytes作为其缓冲区的ByteArrayInputStream对象 ByteArrayInputStream bais = new ByteArrayInputStream(bytes); //创建从底层输入流中读取数据的缓冲输入流对象 bin = new BufferedInputStream(bais); //创建到指定文件的输出流 fout = new FileOutputStream(file); //为文件输出流对接缓冲输出流对象 bout = new BufferedOutputStream(fout); byte[] buffers = new byte[1024]; int len = bin.read(buffers); while(len != -1){ bout.write(buffers, 0, len); len = bin.read(buffers); } //刷新此输出流并强制写出所有缓冲的输出字节,必须这行代码,否则有可能有问题 bout.flush(); } catch (IOException e) { e.printStackTrace(); } finally { try { bout.close(); fout.close(); bin.close(); } catch (IOException e) { e.printStackTrace(); } } } 前台是将页面展示的数据图标什么的生成PDF 前台代码: function downloadofpdf(){ var varname = $("#taskid").text(); if(confirm("您确认下载该PDF文件吗?")){ var target = document.getElementById("bodyid"); target.style.background = "#FFFFFF"; // if(pdfName==''||pdfName==undefined) pdfName= getNowFormatDate(); html2canvas(target, { onrendered:function(canvas) { var contentWidth = canvas.width; var contentHeight = canvas.height; //一页pdf显示html页面生成的canvas高度; var pageHeight = contentWidth /1592.28 * 841.89; //未生成pdf的html页面高度 var leftHeight = contentHeight; //页面偏移 var position = 0; //a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf图片的宽高 var imgWidth = 595.28; var imgHeight = 592.28/contentWidth * contentHeight; var pageData = canvas.toDataURL('image/jpeg', 1.0); var pdf = new jsPDF('', 'pt', 'a4'); //有两个高度需要区分,一个是html页面的实际高度,和生成pdf的页面高度(841.89) //当内容未超过pdf一页显示的范围,无需分页 if (leftHeight < pageHeight) { pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight ); } else { while(leftHeight > 0) { pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight); leftHeight -= pageHeight; position -= 841.89; //避免添加空白页 if(leftHeight > 0) { pdf.addPage(); } } } pdf.save(varname+".pdf"); // 将pdf输入为base格式的字符串 var buffer = pdf.output("datauristring"); // // 将base64格式的字符串换为file文件 // var myfile = dataURLtoFile(buffer, varname); // var formdata = new FormData(); // formdata.append(name, myfile); $.post("/riskManage/uploadpdf",{data:JSON.stringify({formdata:buffer})},function(result){ //alert("hao"); }) //sc(); }, background: "#fff" }) } }
©️2020 CSDN 皮肤主题: 精致技术 设计师: CSDN官方博客 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值