javascript - 使用 React.js 下载图像文件问题。
问题描述
单击下载按钮时,文件会下载,但打开时显示“无法打开此文件”
import * as React from 'react';
import Child from './child';
export interface Props {
}
export interface State {
}
export default class Parent extends React.Component<Props, State> {
constructor(props: Props) {
super(props);
}
render() {
return (
<div>
<Child url="https://images.pexels.com/photos/248797/pexels-photo-248797.jpeg?auto=compress&cs=tinysrgb&h=750&w=1260"/>
</div>
);
}
}
enter code here
// Here is the Child Component
import * as React from 'react';
export interface Props {
url: string;
}
export interface State {
}
export default class Child extends React.Component<Props, State> {
constructor(props: Props) {
super(props);
this.download = this.download.bind(this);
}
download() {
debugger;
var element = document.createElement('a');
var file = new Blob([this.props.url], { type: 'image/*' });
element.href = URL.createObjectURL(file);
element.download = 'image.jpg';
element.click();
}
render() {
return (
<div className="container">
<div className="row">
<img src={this.props.url} />
</div>
<div className="row">
<span onClick={() => { this.download(); }}>Download</span>
</div>
</div>
);
}
}
解决方案
推荐阅读
- jquery - 如何隐藏具有警报成功的所有 td 的 tr?
- python - 如何安装 libavformat.so.56 和 libavformat.so.57?
- python - python post请求未生成响应
- html - 从顶部向下移动/平移时淡入元素的方法?
- c++ - C ++将分配移动到未初始化的对象?
- winforms - 带有 WebBrowser 控件的 WinForms 应用程序中的 html5 视频流没有声音
- phpmyadmin - 无法将任何数据库导入 Xampp PHPmyAdmin 无论大小
- c++ - Objective-C 变量布局
- java - 大米之谜 - 为什么“If else”语句不能正确循环?
- go - 如何填充作为函数引用传递的接口切片