uni-app捣鼓之路--------- 上传图片并转换为base64

uni-app上传文件接口uni.uploadFile 结合uni.chooseImage使用。

前端代码

uni.chooseImage({
		count: 1,//图片数量
		success(res) {
		// console.log(res);
		// 缓存文件路径
		var file = res.tempFilePaths;
		uni.uploadFile({
			url: "http://192.168.0.104:8080/uploadImg", //仅为示例,非真实的接口地址
			filePath: file ,
			name: 'files',
			success: (uploadFileRes) => {
				console.log(uploadFileRes)
			},
			complete() {
				uni.hideLoading()
			}
		});
		},
		fail(err) {
			console.log(err)
			reject(err)
		}
	})

后台代码

byte[] data = null;
// 读取图片字节数组
try {
    InputStream in = files.getInputStream();
    data = new byte[in.available()];
    in.read(data);
    in.close();
} catch (IOException e) {
    e.printStackTrace();
}
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
// 返回Base64编码过的字节数组字符串
String img = "data:image/jpg;base64,"+encoder.encode(data != null ? data : new byte[0]);
System.out.println("本地图片转换Base64:" + img);

注意:转换后的base64在uni-app不能显示,可能是因为有换行符,替换即可

img.replace(/[\r\n]/g, "")
posted @ 2020-02-14 13:35  孙振光  阅读(386)  评论(0编辑  收藏  举报