ko_ma
ko_ma

Reputation: 1021

How to set backgroundImage from input file?

I hope to set background image from input local file.

But it occurs 'net::ERR_UNKNOWN_URL_SCHEME' error message.

My input tag:

<input
  accept="image/*"
  className="input_img"
  type="file"
  onChange={e => this.uploadImage(e)}
/>

My uploadImage function:

uploadImage = e => {
   let node = document.getElementById("result");

   node.style.backgroundImage = "url(" + e.target.result + ")";
};

How do I do it?

Upvotes: 2

Views: 1441

Answers (1)

Tholle
Tholle

Reputation: 112787

You could use a FileReader to read the data of the file, and then set the backgroundImage with the result.

Example

class App extends Component {
  uploadImage = (e) => {
    const { files } = e.target;
    if (files.length === 0) {
      return;
    }

    const file = files[0];
    const fileReader = new FileReader();

    fileReader.onload = () => {
      this.background.style.backgroundImage = `url(${fileReader.result})`;
    };
    fileReader.readAsDataURL(file);
  };

  render() {
    return (
      <div>
        <input
          accept="image/*"
          className="input_img"
          type="file"
          onChange={this.uploadImage}
        />
        <div
          style={{width: 200, height: 200}}
          ref={ref => this.background = ref}
        ></div>
      </div>
    );
  }
}

Upvotes: 2

Related Questions