0
votes

What I want to achieve is when the user press choosefile and chooses an image file, js would save the image file in the directory and use it. Thanks in advance :) here is my HTML: <Upload onChange={this.onChangeUrl}> <Button> <UploadOutlined /> Click to Upload </Button> </Upload> <Button onClick={this.onSubmit}> Add Card</Button> Here is the error I get: xhr.js:178 POST http://localhost:3000/add 404 (Not Found) createError.js:16 Uncaught (in promise) Error: Request failed with status code 404 at createError (createError.js:16) at settle (settle.js:17) at XMLHttpRequest.handleLoad (xhr.js:61)

Is there a post request that I should implement?

2
Please add the code you already have. - Cosmin Staicu
Does this answer your question? How to upload an image in React JS? - Alien

2 Answers

0
votes

Installation Axios: Run the below command.

npm install axios --save

Example:

import axios from 'axios'; 

import React,{Component} from 'react'; 

class App extends Component { 

    state = { 

    // Initially, no file is selected 
    selectedFile: null
    }; 
    
    // On file select (from the pop up) 
    onFileChange = event => { 
    
    // Update the state 
    this.setState({ selectedFile: event.target.files[0] }); 
    
    }; 
    
    // On file upload (click the upload button) 
    onFileUpload = () => { 
    
    // Create an object of formData 
    const formData = new FormData(); 
    
    // Update the formData object 
    formData.append( 
        "myFile", 
        this.state.selectedFile, 
        this.state.selectedFile.name 
    ); 
    
    // Details of the uploaded file 
    console.log(this.state.selectedFile); 
    
    // Request made to the backend api 
    // Send formData object 
    axios.post("api/uploadfile", formData); 
    }; 
    
    // File content to be displayed after 
    // file upload is complete 
    fileData = () => { 
    
    if (this.state.selectedFile) { 
        
        return ( 
        <div> 
            <h2>File Details:</h2> 
            <p>File Name: {this.state.selectedFile.name}</p> 
            <p>File Type: {this.state.selectedFile.type}</p> 
            <p> 
            Last Modified:{" "} 
            {this.state.selectedFile.lastModifiedDate.toDateString()} 
            </p> 
        </div> 
        ); 
    } else { 
        return ( 
        <div> 
            <br /> 
            <h4>Choose before Pressing the Upload button</h4> 
        </div> 
        ); 
    } 
    }; 
    
    render() { 
    
    return ( 
        <div> 
            <h1> 
            GeeksforGeeks 
            </h1> 
            <h3> 
            File Upload using React! 
            </h3> 
            <div> 
                <input type="file" onChange={this.onFileChange} /> 
                <button onClick={this.onFileUpload}> 
                Upload! 
                </button> 
            </div> 
        {this.fileData()} 
        </div> 
    ); 
    } 
} 

export default App; 
0
votes

HTML

<form onSubmit={this.onFormSubmit}>
  <h3>Upload Profile Picture</h3>
  <input type="file" name="userPhoto" onChange={this.onChange} />
  <button type="submit">Upload</button>
</form>

JS

import { uploadPicture } from "./Actions";

onChange(e) {
  this.setState({ file: e.target.files[0] });
}
onFormSubmit(e) {
    e.preventDefault();
    const formData = new FormData();
    formData.append("usrPhoto", this.state.file);
    uploadPicture(formData)
      .then((res) => {
        console.log(res);
      });
  }

Action.JS

export const uploadPicture = (formData) {
  const config = {
    headers: {
      "content-type": "multipart/form-data",
    },
  };
  return axios
    .post([YOUR APP URL] + "api/user/updatePicture", formData, config)
    .then(function (response) {
      console.log(response.data)
    })
    .catch(function (error) {
      //  some error occurred
      return [];
    });
};

In this.state.file you have image data hit request on the server to save on directory.