简体   繁体   中英

Upload a file from react native image picker to server

can someone tell me what im 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?

               data.append('image', {
                        uri: filename,
                        name: 'test.jpg',
                        type: 'image/jpeg'
                         });

Image upload format should be this and please check file url should be correct.

"uri": "file:///Users/user/Library/Developer/CoreSimulator/Devices/33198C8D-55D3-4555-B9B5-DC1A61761AAF/data/Containers/Data/Application/B5067299-1CD2-4000-8935-59B59ED447F6/tmp/871EB6D5-2408-4A10-8DE7-EE52B1855ECD.jpg"

this is url for image. it should be like this.

 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) => {
   
  })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM