本地后端提供一个代理接口,接口返回可跨域 的头部,前端对于跨域的图片将url作为参数传递到代理接口,代理接口根据传递的url 直接下载资源。
代理接口:
app.MapGet("/proxy", httpcontext =>
{
var url = httpcontext.Request.Query["url"].ToString();
var contentType = httpcontext.Request.Query["contenttype"].ToString();
url = System.Web.HttpUtility.UrlDecode(url);
HttpClient client = new HttpClient();
byte[] bytes = client.GetByteArrayAsync(url).Result;
httpcontext.Response.Headers.TryAdd("Access-Control-Allow-Origin", "*");
httpcontext.Response.Headers.TryAdd("Content-type", string.IsNullOrEmpty(contentType)?"application/octet-stream": contentType);
return httpcontext.Response.Body.WriteAsync(bytes).AsTask();
//httpcontext.Response.Body.Flush();
});
前端处理:
(此处的 http://localhost:7230/proxy 就是代理的api)
var imglist = document.getElementsByTagName("img");
for (let i = 0; i < imglist.length; i++) {
let imgObj = imglist[i];
imgObj.src = "http://localhost:7230/proxy?url=" + encodeURI(imgObj.src);
}