1、接收的是字節數組
axios .get('/avatar', { params: param, responseType: 'arraybuffer' }) .then(response => { return 'data:image/png;base64,' + btoa( new Uint8Array(response.data) .reduce((data, byte) => data + String.fromCharCode(byte), '') ); }).then(data => { ... })
2、項目中的后端
@GetMapping(value = "/avatar") public byte[] getUserAvatar() { return this.sysUserService.getUserAvatarByUserId(SecurityUtils.getCurrentUserId()); } public byte[] getUserAvatarByUserId(String id) { SysUserAvatar userAvatar = this.sysUserAvatarDao.queryById(SecurityUtils.getCurrentUserId()); if(userAvatar == null) return new byte[0]; File file = new File(userAvatar.getPath()); if(!file.exists()) return new byte[0]; FileInputStream inputStream = null; byte[] bytes = null; try { inputStream = new FileInputStream(file); bytes = new byte[inputStream.available()]; int read = inputStream.read(bytes, 0, inputStream.available()); log.info("讀取用戶頭像數據:"+read+"字節"); } catch (Exception e) { e.printStackTrace(); throw new CommonException(StatusCode.ERROR,"讀取文件錯誤"); }finally { IoUtil.close(inputStream); } return bytes; }
3、vue項目中的前端
// 獲取頭像圖片的字節數組byte[] export function getAvatar() { return request({ url: `api/users/avatar`, method: 'get', responseType: 'arraybuffer' }) }
getUserAvatar() { getAvatar().then(res => { this.AvatarData = 'data:image/png;base64,' + btoa( new Uint8Array(res.data) .reduce((data, byte) => data + String.fromCharCode(byte), '')) }) }
<img :src="user.avatar ? AvatarData : Avatar" title="點擊上傳頭像" class="avatar">
4、補充,要是后端是不是字節數組返回,而是通過response的blob類型返回
// 使用axios請求上傳接口 axios({ method: 'get', url: url, // 請求地址 responseType: 'blob' // 設置接收格式為blob格式 }).then(res => { // console.log(res) if (res && res.data && res.data.size) { const dataInfo = res.data let reader = new window.FileReader() // 使用readAsArrayBuffer讀取文件, result屬性中將包含一個 ArrayBuffer 對象以表示所讀取文件的數據 reader.readAsArrayBuffer(dataInfo) reader.onload = function (e) { const result = e.target.result const contentType = dataInfo.type // 生成blob圖片,需要參數(字節數組, 文件類型) const blob = new Blob([result], { type: contentType }) // 使用 Blob 創建一個指向類型化數組的URL, URL.createObjectURL是new Blob文件的方法,可以生成一個普通的url,可以直接使用,比如用在img.src上 const url = window.URL.createObjectURL(blob) console.log(url) // 產生一個類似 blob:d3958f5c-0777-0845-9dcf-2cb28783acaf 這樣的URL字符串 } } })