前端使用XMLHttpRequest实现通过链接下载图片
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="button" value="test" onclick="test()">
<script>
const fileInfo = {
url: 'https://res.hc-cdn.com/cnpm-common-resource/2.0.2/base/header/components/images/logo.png',
name: 'a.png'
}
function test() {
downloadUrlFile(fileInfo.url)
}
function downloadUrlFile(url) {
const xhr = new XMLHttpRequest()
xhr.open('GET', url, true)
xhr.responseType = 'blob'
xhr.onload = () => {
if (xhr.status === 200) {
saveAs(xhr.response, fileInfo.name)
}
}
xhr.send()
}
function saveAs(data, name) {
var urlObject = window.URL || window.webkitURL || window;

本文介绍了如何在前端利用XMLHttpRequest技术实现从指定链接下载图片,涵盖了Ajax请求、跨域处理等关键步骤,旨在帮助开发者掌握前端文件下载的方法。
最低0.47元/天 解锁文章
8584

被折叠的 条评论
为什么被折叠?



