<template><view class="content"><view class="button"><button @click="chooseFile" value="请选择文件">请选择文件</button></view><view class="img" v-for="imgPath in imgPaths"><image class="img_img" :src="imgPath"></image></view><button @click="getImg">savsaf</button><image :src="QRImg"></image></view></template><script>export default {data() {return {imgPaths:[], //上传的图片保存QRImg:"" //查询的图片base64编码保存}},methods: {async getImg() {uni.request({url:'http://localhost:6003/Manage/test',method:'POST',responseType: "arraybuffer",success: (res) => {//将arrayBuffer数据转换成base64格式即可显示,这里的uni.arrayBufferToBase64(res.data)使用substring是因为不知道为什么会多出196个字符,删掉就可以显示图片了this.QRImg = 'data:image/jpeg;base64,'+ uni.arrayBufferToBase64(res.data).substring(196,uni.arrayBufferToBase64(res.data).length)}})},chooseFile(e){var that = this;uni.chooseImage({count: 9, //默认9sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有sourceType: ['album'], //从相册选择success: function (res) {that.imgPaths = res.tempFilePaths;for (var i = 0; i < that.imgPaths.length; i++) {uni.uploadFile({url: 'http://localhost:6003/Manage/uploadImg', //仅为示例,非真实的接口地址filePath: that.imgPaths[i],name: 'uploadFile',formData: {'user': 'test'},success: (uploadFileRes) => {console.log(uploadFileRes);}});}}});}}}</script>
SpringBoot后端测试代码,另外数据库中字段为Blob(MediumBlob、LongBlob)类型。
//插入图片到数据库,格式为blob@PostMapping("/uploadImg")public void uploadImg(MultipartFile uploadFile, HttpServletRequest req) throws IOException, SQLException {Blob blob = new SerialBlob(uploadFile.getBytes());houseimgMapper.insertimg(blob);}//将数据库获取到的blob返回给前端/*** 图片路径*///注意,我的实体类定义img的类型为: private byte[] imgurl;@PostMapping("/test")public ResponseEntity<byte[]> uploadImg() throws IOException, SQLException {byte[] imageContent = houseimgMapper.selectById(5).getImgurl();return new ResponseEntity<>(imageContent, HttpStatus.OK);}