最近遇到react native中需要上传一些图片到后台.期间,找了一些第三方上传插件,感觉不太好用,要么只支持一个平台,要么会对其他第三方造成影响,实在无奈.只能直接使用fetch上传.其中上传文件只需要图片的绝对路径即可,可能RN底层会帮我们把图片转为流传输

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/*
 *
 *   上传图片请求
 *   @param
 *   @returns
 * */
 
uploadImage(imgAry) {
    let formData = new FormData();<br>       //因为需要上传多张图片,所以需要遍历数组,把图片的路径数组放入formData中
    for(var i = 0;i<imgAry.length;i++){
        let file = {uri: imgAry[i], type: 'multipart/form-data', name: 'image.png'};   //这里的key(uri和type和name)不能改变,
        formData.append("files",file);   //这里的files就是后台需要的key
    }
    fetch('http://192.168.0.183:8080/whale/test/upload_files',{
        method:'POST',
        headers:{
            'Content-Type':'multipart/form-data',
        },
        body:formData,
    })
        .then((response) => response.text() )
        .then((responseData)=>{
 
            console.log('responseData',responseData);
        })
        .catch((error)=>{console.error('error',error)});
}

 其中,关于图片的路径,我的是这样的:

iOS:

file:///Users/shaotingzhou/Library/Developer/CoreSimulator/Devices/9462ED30-88C7-4318-BF83-3914B9314D34/data/Containers/Data/Application/E9A05CAF-AF07-4BA3-B2C3-C2EFBC6C2C6A/Documents/images/D5E1640B-836A-4EC9-A5C2-65B2E4E8CFE0.jpg

Android: 

file:///storage/emulated/0/Pictures/image-ec0667ed-ecc5-4eed-928f-26fed6a63860.jpg

上传成功截图: