繁体   English   中英

从反应本机图像选择器上传文件到服务器

[英]Upload a file from react native image picker to server

有人能告诉我我做错了什么我不断收到错误 400 错误请求,我似乎无法弄清楚如何发送图像我试图发送路径、文件名和 mime 但它不起作用这是我的请求:

 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); } }); };

这是我的模型:

 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

我如何编写请求以使其被服务器接受?

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

图片上传格式应该是这个,请检查文件 url 是否正确。

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

这是图片的网址。 它应该是这样的。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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