2015-09-07 115 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: '', 
     }; 
     } 
    }); 
    } 
}