首页 > 解决方案 > 使用 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>
        );
    }

}

标签: javascriptreactjs

解决方案


推荐阅读