对于跨域的图片使用base64的形式。
download(imageUrl) async {
final http.Response r = await http.get(Uri.parse(imageUrl));
final data = r.bodyBytes;
final base64data = base64Encode(data);
final a =
html.AnchorElement(href: 'data:image/jpeg;base64,$base64data');
a.download = md5.convert(utf8.encode(imageUrl)).toString();
a.click();
a.remove();
}
对于视频使用blob的形式。
var xhr = html.HttpRequest();
xhr.open('get', videoUrl);
xhr.responseType = 'arraybuffer';
xhr.onLoad.listen((event) {
final a = html.AnchorElement(
href: html.Url.createObjectUrl(html.Blob([xhr.response])));
a.download = md5.convert(utf8.encode(videoUrl)).toString()+'.mp4';
a.click();
a.remove();
});
xhr.send();
其关键在于html.AnchorElement()创建a标签而不是createElement,不清楚两者区别。
好吧,质量差不让我发,那就废话两句。
前端下载图片的几种方式:
1.ifream + execCommand
const download = (url) => {
? const iframe = document.createElement("iframe");
? iframe.style.display = "none"; // 防止影响页面
? iframe.style.height = 0; // 防止影响页面
? iframe.src = url;
? document.body.appendChild(iframe); // iframe挂在到dom树上才会发请求
? iframe.onload = () => {
? ? iframe.contentWindow.document.execCommand('SaveAs')
? ? document.body.removeChild(iframe)
? }
}
2.location.href和window.open
3.flutter
? ? -- path_provider
? ? -- dio.download
4.a标签+download
```dart var a = html.document.createElement('a'); a.setAttribute('href', href); a.setAttribute('download', title); ?a.click(); ```
5.blob
6.a标签+base64
finalhttp.Responser=await http.get(Uri.parse(imageUrl) );
finaldata=r.bodyBytes;
finalbase64data=base64Encode(data);
finala=html.AnchorElement(href:'data:image/jpeg;base64,$base64data');
a.download = md5.convert(utf8.encode(imageUrl)).toString();
a.click();
a.remove();
|