React Native 程式碼片段
阿新 • • 發佈:2019-01-05
一. Upload Image – fetch
export function postData (url, params, fileURL) {
let data = new FormData()
if (fileURL) {
data.append('image', {uri: fileURL, name: 'image.jpg', type: 'image/jpg'})
}
_.each(params, (value, key) => {
if (value instanceof Date) {
data.append(key, value. toISOString())
} else {
data.append(key, String(value))
}
})
const config = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data; boundary=6ff46e0b6b5148d984f148b6542e5a5d',
'Content-Language': React.NativeModules.RNI18n. locale,
'Authorization': 'Token ABCDEF123457890',
},
body: data,
}
return fetch(API_URL + url, config)
.then(checkStatusAndGetJSONResponse)
}
var options = {
title: 'Upload image',
cancelButtonTitle: 'Cancel',
takePhotoButtonTitle: 'Take Photo...',
chooseFromLibraryButtonTitle : 'Choose from Library...',
returnBase64Image: true,
returnIsVertical: false
};
UIImagePickerManager.showImagePicker(options, (type, response) => {
if (type !== 'cancel') {
var source;
if (type === 'data') {
source = {uri: 'data:image/jpeg;base64,' + response, isStatic: true};
} else {
source = {uri: response};
}
console.log("uploading image");
fetch('server-endpoint',{
method: 'post',
body: "data=" + encodeURIComponent(source.uri)
}).then(response => {
console.log("image uploaded")
console.log(response)
}).catch(console.log);
//this.setState({avatarSource:source});
} else {
console.log('Cancel');
}
});