通过form表单上传图片时,有时候web容器对文件大小的限制会影响我们上传。这时,前端页面可以考虑将图片转换成base64串来实现上传。
图片与base64的互转,其实就是利用了文件流与base64的互转。
文件转换成base64字符串:读取文件流,放到byte数组里,对byte数组进行base64编码,返回字符串。
base64串转换成文件:对base64串进行解码,得到byte数组,利用文件输出流将byte数据写入到文件。
talk is cheap, show me the code。直接上代码:
import sun.misc.base64decoder;
import sun.misc.base64encoder;
import java.io.*;
public class imagebase64converter {
/**
* 本地文件(图片、excel等)转换成base64字符串
*
* @param imgpath
*/
public static string convertfiletobase64(string imgpath) {
byte[] data = null;
// 读取图片字节数组
try {
inputstream in = new fileinputstream(imgpath);
system.out.println("文件大小(字节)="+in.available());
data = new byte[in.available()];
in.read(data);
in.close();
} catch (ioexception e) {
e.printstacktrace();
}
// 对字节数组进行base64编码,得到base64编码的字符串
base64encoder encoder = new base64encoder();
string base64str = encoder.encode(data);
return base64str;
}
/**
* 将base64字符串,生成文件
*/
public static file convertbase64tofile(string filebase64string, string filepath, string filename) {
bufferedoutputstream bos = null;
fileoutputstream fos = null;
file file = null;
try {
file dir = new file(filepath);
if (!dir.exists() && dir.isdirectory()) {//判断文件目录是否存在
dir.mkdirs();
}
base64decoder decoder = new base64decoder();
byte[] bfile = decoder.decodebuffer(filebase64string);
file = new file(filepath + file.separator + filename);
fos = new fileoutputstream(file);
bos = new bufferedoutputstream(fos);
bos.write(bfile);
return file;
} catch (exception e) {
e.printstacktrace();
return null;
} finally {
if (bos != null) {
try {
bos.close();
} catch (ioexception e1) {
e1.printstacktrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (ioexception e1) {
e1.printstacktrace();
}
}
}
}
}
test:
public static void main(string[] args) {
long start = system.currenttimemillis();
string imgbase64str= imagebase64converter.convertfiletobase64("c:\\users\\zhangguozhan\\pictures\\科技\\liziqi-李子柒爆红.jpg");
// system.out.println("本地图片转换base64:" + imgbase64str);
system.out.println("base64字符串length="+imgbase64str.length());
imagebase64converter.convertbase64tofile(imgbase64str,"c:\\users\\zhangguozhan\\pictures\\科技","test.jpg");
system.out.println("duration:"+(system.currenttimemillis()-start));
start=system.currenttimemillis();
string filebase64str= imagebase64converter.convertfiletobase64("c:\\users\\zhangguozhan\\pictures\\科技\\payorderlist200109075516581.xlsx");
// system.out.println("本地excel转换base64:" + filebase64str);
system.out.println("size="+filebase64str.length());
imagebase64converter.convertbase64tofile(filebase64str,"c:\\users\\zhangguozhan\\pictures\\科技","test.xlsx");
system.out.println("duration:"+(system.currenttimemillis()-start));
}
执行结果:
文件大小(字节)=2820811
base64字符串length=3860058
duration:244
文件大小(字节)=25506
size=34902
duration:10
提醒一下:获取文件的大小是用fileinputstream实例的available()方法哦,用file实例的length()返回的是0。
如下图,测试方法里图片文件“liziqi-李子柒爆红.jpg”的大小正是2820811字节 ÷1024=2755kb ÷1024=2.68m
希望与广大网友互动??
点此进行留言吧!