如何上传带有表单数据的图像?

Jef*_*uel 0 react-native expo

我正在通过 Expo 学习 React Native。对于测试项目,我有一个名为“创建配置文件”的屏幕,我试图在其中添加在 Expo 图像选择器上选择的图像以及其他文本输入(位置、描述)。如何将输入与图像选择器中的图像组合起来?

我当前的猜测是对图像使用 base64 或将图像输入设置为“this.state.image”以从选择器中调用 image:uri。尽管我可能走错了路。另一种选择是使用 Content-Type:multipart-form/data,尽管尝试时它不会将任何数据发布到 API 调用。

该 API 是使用 Django Rest Framework 在 Django 应用程序上构建的。

我的代码如下: render() { let { image } = this.state;

function handleSubmit(props) {
  fetch('<API URL HERE>', {
    method: 'POST',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
    }, 
    body:JSON.stringify({
      'location': this.state.location,
      'description': this.state.description,
      //user image field and input below
      'user_image':this.state.image


    })
  });
} 
Run Code Online (Sandbox Code Playgroud)

图像选择器

_pickImage = async () => {
try {
  let result = await ImagePicker.launchImageLibraryAsync({
    mediaTypes: ImagePicker.MediaTypeOptions.All,
    allowsEditing: true,
    aspect: [4, 3],
    quality: 1,
  });
  if (!result.cancelled) {
    const image = result.uri;
    this.setState({ image: result.uri });
  }

  console.log(result);
} catch (E) {
  console.log(E);
}
Run Code Online (Sandbox Code Playgroud)

};

Jef*_*uel 5

我刚刚设法解决了这个问题,为了其他想要类似结果的人的利益,我将其发布在这里。

  1. 对于图像选择器,您需要添加其他变量,例如图像 uri、文件名和文件类型。

      _pickImage = async () => {
       try {
       let result = await ImagePicker.launchImageLibraryAsync({
         mediaTypes: ImagePicker.MediaTypeOptions.All,
    allowsEditing: true,
    aspect: [4, 3],
    quality: 1,
       });
         if (!result.cancelled) {
    this.setState({ image: result.uri });
    
    let localUri = result.uri;
    let filename = localUri.split('/').pop();
    
    // Infer the type of the image
    let match = /\.(\w+)$/.exec(filename);
    let type = match ? `image/${match[1]}` : `image`;
    
    this.setState({ localUri: result.uri });
    this.setState({ filename: filename });
    this.setState({ type: type });
    
      }
    
    Run Code Online (Sandbox Code Playgroud)

然后,对于表单数据,您必须在将图像字段与其他字段一起提交时调整图像字段以包含这些变量。

    let formData = new FormData();
    formData.append('location',this.state.location);
    formData.append('description',this.state.description);
    formData.append('member_unique','IEQ'); 
    formData.append('user_image', {type:type, uri:uri, name:filename});

 function handleSubmit(props) {
  fetch('<posting api>', {
    method: 'POST',
    body:formData, 

  });
}
Run Code Online (Sandbox Code Playgroud)