ios 如何使用ReactNative在服务器上上传图像

hi3rlvi2  于 2022-12-15  发布在  iOS
关注(0)|答案(4)|浏览(152)

我正在设置标题和正文,使用后提取上传服务器上的图像。我得到的响应代码200,但它不是上传图像,但其余的数据正在上传。
下面是body的代码:

export default function setRequestBody(imagePath){

    let boundry = "----WebKitFormBoundaryIOASRrUAgzuadr8l";

    let body = new FormData();

    body.append("--"+boundry+"\r\n");
    body.append("Content-Disposition: form-data; name=imageCaption\r\n\r\n");
    body.append("Caption"+"\r\n");
    body.append("--"+boundry+"\r\n");
    body.append("Content-Disposition: form-data; name=imageFormKey; filename =iimageName.pngg \r\n");
    body.append("Content-Type: image/png \r\n\r\n");
    body.append({uri : imagePath});
    // appened image Data Here
    body.append("\r\n");
    body.append("--"+boundry+"--\r\n");
    return body

}

请帮帮忙。我犯了什么错误。

a2mppw5e

a2mppw5e1#

我找到了解决办法:

let body = new FormData();
body.append('photo', {uri: imagePath,name: 'photo.png',filename :'imageName.png',type: 'image/png'});
body.append('Content-Type', 'image/png');

fetch(Url,{ method: 'POST',headers:{  
     "Content-Type": "multipart/form-data",
     "otherHeader": "foo",
     } , body :body} )
  .then((res) => checkStatus(res))
  .then((res) => res.json())
  .then((res) => { console.log("response" +JSON.stringify(res)); })
  .catch((e) => console.log(e))
  .done()

**文件名是可选的...

0mkxixxg

0mkxixxg2#

问题是body.append({uri : imagePath});,因为react原生JSC不支持File和Blob,所以必须使用库。
react-native-fetch-blob对此提供了很好的支持,例如其README.md

RNFetchBlob.fetch('POST', 'http://www.example.com/upload-form', {
        Authorization : "Bearer access-token",
        otherHeader : "foo",
        'Content-Type' : 'multipart/form-data',
    }, [
    // element with property `filename` will be transformed into `file` in form data
    { name : 'avatar', filename : 'avatar.png', data: binaryDataInBase64},
    // custom content type
    { name : 'avatar-png', filename : 'avatar-png.png', type:'image/png', data: binaryDataInBase64},
    // part file from storage
    { name : 'avatar-foo', filename : 'avatar-foo.png', type:'image/foo', data: RNFetchBlob.wrap(path_to_a_file)},
    // elements without property `filename` will be sent as plain text
    { name : 'name', data : 'user'},
    { name : 'info', data : JSON.stringify({
      mail : 'example@example.com',
      tel : '12345678'
    })},
  ]).then((resp) => {
    // ...
  }).catch((err) => {
    // ...
  })
z9zf31ra

z9zf31ra3#

我已经找到了在React Native中上传服务器上的图像的解决方案:

const formdata = new FormData();
formdata.append('image[]', {
          name: 'test.' + imageurl?.type?.substr(6),
          type: imageurl?.type,
          uri:
            Platform.OS !== 'android'
              ? 'file://' + imageurl?.uri
              : imageurl?.uri,
        });
const res = await axios.post(url, formdata, {
        headers: {
          Accept: '*/*',
          'Content-type': 'multipart/form-data',
        },
      });
tv6aics1

tv6aics14#

//首先安装并导入Image-piker //安装

npm i react-native-image-picker

//输入

import * as ImagePicker from 'expo-image-picker';

//然后

const [image, setImage] = React.useState(null);
const [Type,setType]=React.useState('')

//获取图像

const pickImage = async () => {
  let result = await ImagePicker.launchImageLibraryAsync({
    mediaTypes: ImagePicker.MediaTypeOptions.All,
    allowsEditing: true,
    aspect: [4, 3],
    quality: 1,
  });

  console.log(result);

  if (!result.cancelled) {
      // extract the filetype
   setType(result.uri.substring(result.uri.lastIndexOf(".") + 1));
 setImage(result.uri);
 
  }
};

//显示图像返回

<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Button title="Ecolher Foto" onPress={pickImage} />
      {image && <Image source={{ uri: image }} style={{ width: 150, height: 150 }} />}
    </View>

//上传图像

var validatinoApi ='https://seusite.com/OOP/';
var headers={
 'Accept':'application/json',
 "Content-Type": "multipart/form-data",
 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
 'Access-Control-Allow-Origin':'*',
 'crossDomain': 'true',
 'Host': 'https://seusite.com/OOP/',
 'Origin': 'https://origem.com',
 
  };
 /*'crossDomain': 'true',*/
 var Data={
  image:image,
  namefoto: `photo.${namefoto}`,
  type: `image/${Type}`

 };

 fetch(validatinoApi,
  {
   method:'POST',
   headers:headers,
   body:JSON.stringify(Data)
 }).then((response)=>response.json())
   .then((response)=>{
     if(response.statusCode==200){
//Do something
}

相关问题