0

I'm trying to upload an image using the code sample given in Codepen

I'm having the file contents in my state variable and getting it in the console from the below mentioned submit function

_handleSubmit(e) {
   e.preventDefault();
   console.log(this.state.file)
   payLoad = {
                image: this.state.file,
            }
   axios({
              method: 'post',
              url: this.state.url+'/task',
              data: payLoad,
              headers: {
                    'content-type': 'multipart/form-data'
                }
            })
 }

My console result of this.state.file is

File(128544)
lastModified:1508143324556
lastModifiedDate:Mon Oct 16 2017 14:12:04 GMT+0530 (India Standard Time) {}
name:"sample.png"
size:128544
type:"image/png"
webkitRelativePath:""
__proto__:File

But the Network shows image variable as {} in API request headers and image is not uploading. Can anyone help? As i'm new to ReactJS I'm really trouble in some features and forced to ask many questions here.

1 Answer 1

1

You need to use FormData, because you are sending a file with content_type as content_type="multipart/form-data".

Try this:

_handleSubmit(e) {
    e.preventDefault();
    console.log(this.state.file)

    let data = new FormData();
    data.append('image', this.state.file);

    axios({
        method: 'post',
        url: this.state.url+'/task',
        data,
        headers: {
            'content-type': 'multipart/form-data'
        }
    })
}

To check the FormData values you can use either FormData.get(key) or iterate over FormData.values() method.

Check this snippet:

let data = new FormData();
data.append('a', 1);
data.append('b', 2);
data.append('c', 3);
data.append('d', 4);

// using formdata.get(key) method
console.log('a = ', data.get('a'));

// iterating over values
for(let el of data.values()){
   console.log('el = ', el);
}

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

6 Comments

So if i need to add more variables, should i append all the values as data.append('id', this.state.id); like this?
yes you can append as many values you want, formdata is needed to send the file otherwise you can send the normal object :)
But in my backend PHP code $_FILES gives null array
not sure about php, check this answer may be solve your issue: stackoverflow.com/questions/17834243/…
Yes, this is the method i'm following and i should get it.But unfortunately not
|

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.