对文件进行base64编码成字符串进行保存或传输

本文介绍了一种在RESTful微服务架构中处理文件传输的方法,即通过Base64编码来实现文件的数据传输,并提供了具体的Java实现代码示例。

       现在微服务很流行,特别是restFull。如果数据格式是json或xml,发现涉及到文件传输时就不太好处理了。网上找到解决方法,就是将文件进行base64编码后再进行传输。当然建议文件不要太大。


  参考了网上的解决方法,自己也测试了下,确实可行。

下面代码来源:http://www.cnblogs.com/mailingfeng/archive/2012/01/09/2317100.html

package com.mai.base64;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.junit.Test;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class Base64Test {

    private String imageURL = "c:/test.png";
    @Test
    public void testBase64Encoder(){
        BASE64Encoder encoder = new BASE64Encoder();
        
        try {
            StringBuilder pictureBuffer = new StringBuilder();
            InputStream input = new FileInputStream(new File(imageURL));
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] temp = new byte[1024];
            for(int len = input.read(temp); len != -1;len = input.read(temp)){
                out.write(temp, 0, len);
                pictureBuffer.append(encoder.encode(out.toByteArray()));
                //out(pictureBuffer.toString());
                out.reset();
            }
            
            out(pictureBuffer.toString());
            out("Encoding the picture Success");
            
            
        
        BASE64Decoder decoder = new BASE64Decoder();
        FileOutputStream write = new FileOutputStream(new File("c:/test2.png"));
        byte[] decoderBytes = decoder.decodeBuffer(pictureBuffer.toString());
        write.write(decoderBytes);
        out("Decoding the picture Success");
            
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e){
            e.printStackTrace();
        }
    }
    
    public void out(Object o){
        System.out.println(o.toString());
    }
}

    如果是项目要使用,建议编码后进行gzip压缩。当要使用时,先接压缩,再解码。

    上面使用的sun.misc.BASE64Decoder,是sun公司内部使用的,没有加入api中。具体位置是jdk的rt.jar里

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值