0

While trying out the following code to load an image file to imgur, using React, ran into problems. The code simply looks for a file test.jpeg, and loads to imgur using imgur's API. App.js starts up with splash screen, as its using (create-react-app) but no file is loaded, the code is as below:

class App extends Component {
  uploadImage() {
    var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;

    const fd = new XMLHttpRequest();
    const Data = new FormData();
    const e = document.getElementsByClassName('Image');
    var t;

    Data.append("image", e);
    fd.open("POST", "https://api.imgur.com/3/image/");

    fd.setRequestHeader("Authorization", "Client ID XXXXSecret");
    fd.onreadystatechange = function() {
      if (fd.status === 200 && fd.readyState === 4) {
        let result = JSON.parse(fd.responseText);
        t = "https://i.imgur.com/${result.data.id}.png";

        const d = document.createElement("div");
        d.className = "image";
        document.getElementByTagName("body")[0].appendChild(d);
      }
    };

    fd.send(Data);
  }
 render() {
return (
  <div className="App">
    <header className="App-header">
      <img src={logo} className="App-logo" alt="logo" />
      <h1 className="App-title">Welcome to React</h1>
    </header>
    <img src={Image} className="ImageFile" alt="Image"/>    
<p className="App-intro">
      To get started, edit <code>src/App.js</code> and save to reload.
    </p>
	 <button onClick={this.uploadImage} width="200" height="200">Button </button>
	 <p></p>
  </div>
);
  }
}
export default App;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

1 Answer 1

1

There's a handful of things wrong here.

  1. Nothing calls uploadImage(), so of course nothing will happen.
  2. Doing Data.append("image", "test.jpeg"); will add a field called image, with a string payload "test.jpeg", not an image called test.jpeg.
  3. If you expect this to be an user-supplied image, you have to use an <input type="file"> element and capture the File object from its files list property. There is no other way of accessing user content.
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, for reply, actually I am getting a list of image files, which is in json, after the user chooses one file the chosen file is to be sent using the api,

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.