我不想让用户知道图片的真实 URL,那么如何在响应中返回图片流,即返回的不是一个浏览器可直接下载的图片文件 URL,而是图片的字节流?
laravel
//Controller //自行设置路由 public function getImg() { //图片链接 $fullPath = 'https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/175b22f0032803f8bdbd94590c8c6629.jpeg'; return response()->stream(function () use ($fullPath) { echo file_get_contents($fullPath); }, 200, ['Content-Type' => 'image/jpeg']); }
vue
//js export default { data() { return { imgUrl:'' } }, methods: { getImg() { axios({ method: 'get', timeout: 50000, baseURL: process.env.BASE_URL, url: '', //填写自己的路径 responseType: 'blob', params: {}, headers: { 'apply-secret': process.env.PROJECT_KEY }, }).then(res => { let blob = new Blob([res.data], { type: 'image/jpeg' }); const imageUrl = URL.createObjectURL(blob); this.imgUrl = imageUrl; }) }, } }
//html <el-image :src="imgUrl" />
最终路径结果