(1)base64格式的图片是文本格式,占用内存小,转换后的大小比例大概为1/3,降低了资源服务器的消耗;
(2)网页中使用base64格式的图片时,不用再请求服务器调用图片资源,减少了服务器访问次数。
uni.chooseImage({
count: 1,
sizeType: ['original', 'compressed'],
sourceType: ['album'], //这要注意,camera调拍照,album是打开手机相册
success: (res) => {
plus.io.resolveLocalFileSystemURL(res.tempFilePaths[0], function(entry) {
// 可通过entry对象操作test.html文件
entry.file(function(file) {
var fileReader = new plus.io.FileReader();
fileReader.readAsDataURL(file);
fileReader.onloadend = function(evt) {
//evt.target.result为已转base64数据
//上传服务器的方法
that.upLoad(evt.target.result);
}
})
})
}
})
后端处理
#上传文件路径
file.path=D:\\upload
#文件访问url
file.http.path=http://127.0.0.1:8080/files/
#文件访问路径
file.dir=file\:D:/upload/
BASE64Decoder decoder = new BASE64Decoder();
try {
String url = params.getFile().split(",")[1];
byte[] b = decoder.decodeBuffer(url);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {
b[i] += 256;
}
}
String path = this.path;
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
String newFileName = uuid + ".jpg";
String src = path + "/" + newFileName;
File dest = new File(src);
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdir();
}
OutputStream out = new FileOutputStream(dest);
out.write(b);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}