1

I'm using Reactjs in frontend.

I've set the profilePicture to state with this code

    handleImageChange = (event) => {
        event.preventDefault();
        var file = event.target.files[0];
        var reader = new FileReader();
        reader.readAsDataURL(file);

        reader.onloadend = function (e) {
            this.setState({
                profilePicture: e.target.result //don't know how it is working 
            });
        }.bind(this);
    }

and I can preview the image file:

<img src={this.state.profilePicture} alt="img"/>

I want to send these data to server:

data = {
    'profilePicture': anImageFile,//this.state.profilePicture
    'photos': [anotherImage, anotherImage2, anotherImage3],
    'personal_info': {
        'name': 'User Name',
        'anyList': [1,2,3]
    }
}

Can I do it using fetch?

5
  • If this.state.profilePicture is just a data url (like data:image/png,...) you can just send that as the profile picture in the request. Commented Jan 4, 2022 at 5:55
  • It converted to base64 (like data:image/png;base64,iVBORw0K...) and the url is too long. Commented Jan 4, 2022 at 6:00
  • is it safe to decode the base64 to image file in backend(Django)? Commented Jan 4, 2022 at 6:02
  • Too long in what way? Is the server blocking the request? A lot of servers are configured to block requests that are larger than 2-5MB. Commented Jan 4, 2022 at 6:02
  • Re: decoding -- yes it's safe Commented Jan 4, 2022 at 6:03

1 Answer 1

1

You can simply do like this:

handleImageChange = (event) => {
        this.setState({profilePicture: event.target.files[0]});
    }

Render Func

<img src={URL.createObjectURL(this.state.profilePicture)} alt="img"/>

And send data object as it is

Sign up to request clarification or add additional context in comments.

Comments

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.