Upload File with React Js

217 views Asked by At

I want to upload a file using React js (fetch) . I upload it with postman with header 'application/x-www-form-urlencoded' and I can upload it now I want to upload it with JS . my Code:

 function FileOnChange(e){
      let file=e.target.files;
      let reader = new FileReader();
      reader.readAsArrayBuffer(file[0])
                reader.onload = function () {
                    var data = reader.result;
                    //var array = new Int8Array(data);
                        var headers={
                        'Content-Type':'application/x-www-form-urlencoded',
                        'authorization':token
                    }   
                     const url=`${SITE}api/upload_avatar_profile/`;
                    fetch(url,{
                      method:'PUT',
                      headers:headers,
                      body:{
                          avatar:file[0]
                      }
                    }).then((response)=>{
                        return response.json();
                    }).then((data)=>{
                          
                       console.log(data)
                            });
                };
    }

anyone can help me. backend is django

1

There are 1 answers

0
mohamadreza ch On
function FileOnChange(e){
  const file=e.target.files;
  const form_data=new FormData()
  form_data.append('avatar',file[0])
                    var headers={
                    'authorization': token
                }   
                 const url=`${SITE}api/upload_avatar_profile/`;
                fetch(url,{
                  method:'PUT',
                  headers:headers,
                  body:form_data   
                }).then((response)=>{
                    return response.json();
                }).then((data)=>{
                  console.log(data);
                        }).then(err => console.log(err));
}