前端
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
window.onload = function(){
var but = document.getElementById('but')
but.onclick=function(){
var xhr = new XMLHttpRequest();
xhr.open('post','http://localhost:8000/img');
xhr.send();
xhr.responseType = 'arraybuffer'
// xhr.setRequestHeader('a','1')
xhr.onprogress = function(e){
console.log(e)
}
xhr.onreadystatechange=function(){
if(xhr.readyState === 4){
if(xhr.status === 200){
// console.log(xhr.response)
console.log(new Blob([xhr.response]))
let body = document.body
let a = document.createElement('a')
a.setAttribute('href',URL.createObjectURL(new Blob([xhr.response])))
a.setAttribute('download','1.jpg')
body.appendChild(a)
a.click()
// let img = document.querySelector('#img')
// img.setAttribute('src',URL.createObjectURL(new Blob([xhr.response])))
}
}
}
}
}
</script>
</head>
<body>
<div>
123
<button id="but">点击</button>
<img src="http://localhost:8000/img" id="img" alt="" width="200" height="200">
</div>
</body>
</html>
后端
var express = require('express') // 缓存
var api = express()
var fs = require('fs')
api.all('*',(req,res,next)=>{
res.setHeader('Access-Control-Allow-Origin','*')
next()
})
api.post('/img',async (req,res)=>{
let pro = function () {
return new Promise((resolve,reject)=>{
fs.readFile('./a.jpg',(err,data)=>{
resolve(data)
reject(err)
})
})
}
let data = await pro()
console.log(data)
res.send(data)
})