2015-09-07 116 views
11

嗨,只是学习使用js和反应原生。我不能使用FormData它总是显示不支持的bodyinit类型。我想发送文本而不是json.stringfy。谁能帮我?谢谢!如何在反应原生态中使用FormData?

var data = new FormData() 
data.append('haha', 'input') 

fetch('http://www.mywebsite.com/search.php', { 
    method: 'post', 
    body: data 
}) 
.then((response) => response.json()) 
.then((responseData) => { 
    console.log('Fetch Success=================='); 
    console.log(responseData); 

    var tempMarker = []; 
    for (var p in responseData) { 
    tempMarker.push({ 
    latitude: responseData[p]['lat'], 
    longitude: responseData[p]['lng'] 
    }) 
    } 

    this.setState({ 
    marker: tempMarker 
    }); 

}) 
.catch((error) => { 
    console.warn(error); 
}) 
.done(); 
+0

什么是实际的错误信息? – jevakallio

+0

“不支持的bodyinit类型” – phongyewtong

回答

9

这为我工作

var serializeJSON = function(data) { 
    return Object.keys(data).map(function (keyName) { 
    return encodeURIComponent(keyName) + '=' + encodeURIComponent(data[keyName]) 
    }).join('&'); 
} 

var response = fetch(url, { 
    method: 'POST', 
    body: serializeJSON({ 
    haha: 'input' 
    }) 
}); 
+2

我该如何使用文本?不是json – phongyewtong

+1

var response = fetch(url,{ method:'POST', body:encodeURIComponent(“haha”)+'='+ encodeURIComponent(“input”) }); –

22

这里是我的简单的代码FORMDATA与反应母语张贴用绳子和形象的要求。

我已经使用反应天然图像选取器与ImagePicker插件来捕获/选择相片 react-native-image-picker

let photo = { uri: source.uri} 
let formdata = new FormData(); 

formdata.append("product[name]", 'test') 
formdata.append("product[price]", 10) 
formdata.append("product[category_ids][]", 2) 
formdata.append("product[description]", '12dsadadsa') 
formdata.append("product[images_attributes[0][file]]", {uri: photo.uri, name: 'image.jpg', type: 'multipart/form-data'}) 


fetch('http://192.168.1.101:3000/products',{ 
    method: 'post', 
    headers: { 
    'Content-Type': 'multipart/form-data', 
    }, 
    body: formdata 
    }).then(response => { 
    console.log("image uploaded") 
    }).catch(err => { 
    console.log(err) 
    }) 
}); 
+1

我可以知道FormData类从哪里来?我检查了react-native-image-picker,它不在里面 –

+0

FormData带有react-native。 https://github.com/facebook/react-native/blob/master/Libraries/Network/FormData.js –

+1

根据MSDN文档,'FormData'应该有一个'set()'方法(它在Chrome for实例),但显然这在React Native中不可用,所以解决方案确实使用'append()' –

0

我已经使用形式的数据。 ,我得到了它的工作请检查下面的代码

ImagePicker.showImagePicker(options, (response) => { 
    console.log('Response = ', response); 
    if (response.didCancel) { 
    console.log('User cancelled photo picker'); 
    } 
    else if (response.error) { 
    console.log('ImagePicker Error: ', response.error); 
    } 
    else if (response.customButton) { 
    console.log('User tapped custom button: ', response.customButton); 
    } 
    else { 
    fetch(globalConfigs.api_url+"/gallery_upload_mobile",{ 
     method: 'post', 
     headers: { 
     'Accept': 'application/json', 
     'Content-Type': 'application/json' 
    }, 
     , 
    body: JSON.stringify({ 
     data: response.data.toString(), 
     fileName: response.fileName 
    }) 
     }).then(response => { 
     console.log("image uploaded") 
     }).catch(err => { 
     console.log(err) 
     }) 
    } 
}); 
+1

如何通过JSON发送多部分内容(请检查您的内容类型标头) –

+0

@AzeemHassni根据您的评论更新我的答案,因为我使用base64字符串获取图像这就是为什么使用json – akshay

0

提供了一些其他的解决办法;我们也使用react-native-image-picker;而服务器端正在使用koa-multer;这种设置工作良好:

UI

ImagePicker.showImagePicker(options, (response) => { 
     if (response.didCancel) {} 
     else if (response.error) {} 
     else if (response.customButton) {} 
     else { 
     this.props.addPhoto({ // leads to handleAddPhoto() 
      fileName: response.fileName, 
      path: response.path, 
      type: response.type, 
      uri: response.uri, 
      width: response.width, 
      height: response.height, 
     }); 
     } 
    }); 

handleAddPhoto = (photo) => { // photo is the above object 
    uploadImage({ // these 3 properties are required 
     uri: photo.uri, 
     type: photo.type, 
     name: photo.fileName, 
    }).then((data) => { 
     // ... 
    }); 
    } 

客户

export function uploadImage(file) { // so uri, type, name are required properties 
    const formData = new FormData(); 
    formData.append('image', file); 

    return fetch(`${imagePathPrefix}/upload`, { // give something like https://xx.yy.zz/upload/whatever 
    method: 'POST', 
    body: formData, 
    } 
).then(
    response => response.json() 
).then(data => ({ 
    uri: data.uri, 
    filename: data.filename, 
    }) 
).catch(
    error => console.log('uploadImage error:', error) 
); 
} 

服务器

import multer from 'koa-multer'; 
import RouterBase from '../core/router-base'; 

const upload = multer({ dest: 'runtime/upload/' }); 

export default class FileUploadRouter extends RouterBase { 
    setupRoutes({ router }) { 
    router.post('/upload', upload.single('image'), async (ctx, next) => { 
     const file = ctx.req.file; 
     if (file != null) { 
     ctx.body = { 
      uri: file.filename, 
      filename: file.originalname, 
     }; 
     } else { 
     ctx.body = { 
      uri: '', 
      filename: '', 
     }; 
     } 
    }); 
    } 
}