hu7sy
hu7sy

Reputation: 961

Why image is not upload to server with react?

I have to upload image with react to server but put request sent empty image object.

This is function to set state for image

...
fileUpload(event) {
    const companyState = {...this.state.company};
    companyState['image'] = event.target.files[0];
    this.setState({company: companyState});
}
...

This is code to upload image

...
<input type="file" name="image" className="form-control"  accept="image/*" onChange={this.fileUpload}/>
...

This service to send image and i have test it here i got image object with file but when i console requestOptions before fetch request it make image object empty

...
function editCompany(id, companyData){
    const requestOptions = {
        method: 'PUT',
        headers: authHeader(),
        body: JSON.stringify(companyData)
    };
    return fetch(baseUrl+'company/'+id, requestOptions)
            .then(handleResponse)
            .then(company => {
                return company;
            })
}
...

This is my auth header function.

...
export function authHeader() {
    // return authorization header with jwt token
    let AdminUser = JSON.parse(localStorage.getItem('admin-user'));

    if (AdminUser && AdminUser.token) {
        return { 'Authorization': 'Bearer ' + AdminUser.token , 'Content-Type': 'application/json' };
    } else {
        return {};
    }
}

Upvotes: 0

Views: 354

Answers (1)

Vishal Sharma
Vishal Sharma

Reputation: 2610

For uploading files, you shouldn't use JSON stringify (if you're not converting the file into base64) build your request as the sample given below.

let data = new FormData();
data.append('name', params.name);
data.append('age', params.age);
data.append('files[]', params.files); // where params.files is of type FileList

once the data is built, you can make the request as you generally do. You might have to put a condition in your authHeader method to change the header if needed. Like, adding a param to the method hasFiles as authHeader(hasFiles=false) and change the header if needed.

Upvotes: 1

Related Questions