Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload a file from react native image picker to server

can someone tell me what i m doing wrong i keep getting error 400 bad request, i can't seem to figure out how to send the image i tried to send the path, the filename and the mime but it's not working this is my request:

  const [image,setImage]=useState(null)
  const[filename,setFileName]=useState(null)
  const sendpic=async ()=>{
    await ImagePicker.openCamera({
      mediaType:'photo',
      width: 300,
      height: 400,
      cropping: false,
    }).then(image => {
      setImage(image['path']);
    const paths=image['path']
   
    const filename=paths.substring(paths.lastIndexOf('/')+1);
    setFileName(filename);
  console.log(filename)
    console.log(image)
    const data=new FormData();
    data.append('image',filename)
    data.append('title','3aslemajiti')

    const headers={
      Accept:'application/json',
      'Content-Type':'multipart/form-data',
    }
    try{
      const response= axios.post('http://192.168.1.19:8000/Sends/',data,{headers:headers})
      alert('yess!!!!!');
    } 
    catch (error) {
      // handle error
      alert(error.message);
    }
  });
  };

and this is my model:

from django.db import models

# Create your models here.
class Send(models.Model):
    title = models.CharField(max_length=255)
    image=models.ImageField(default ='null')
    def __str__(self):
            return self.title

how do i write the request so it is accepted by the server?

like image 627
Rihab sabri Avatar asked Nov 18 '25 05:11

Rihab sabri


1 Answers

 const data = new FormData();
  
  data.append("uploadFile", {
    name: filename,
    type: filetype,
    uri:
      Platform.OS === "android"
        ? fileuri
        : fileuri.replace("file://", "")
  });
  var url = uploadDoc

  axios.post(url, data, {headers: {
    "Content-Type": "multipart/form-data",
    Accept: "application/json",
    Authorization: authToken

  }})
  .then((res) => {
   
  })
  .catch((err) => {
   
  })
like image 198
Ruchi Tiwari Avatar answered Nov 19 '25 19:11

Ruchi Tiwari



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!