Last active
October 3, 2018 09:54
-
-
Save watanabeyu/1311dd1e9e7317972f266063de7a535d to your computer and use it in GitHub Desktop.
progress fetch
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const progressFetch = (url, options = {}, onProgress = {}) => new Promise((res, rej) => { | |
const xhr = new XMLHttpRequest(); | |
xhr.open(options.method || 'post', url); | |
Object.keys(options.headers || {}).forEach((k) => { | |
xhr.setRequestHeader(k, options.headers[k]); | |
}); | |
xhr.onload = e => res(e.target.responseText); | |
xhr.onerror = rej; | |
if (xhr.upload) { | |
xhr.upload.onprogress = e => onProgress((e.loaded / e.total) * 100); | |
} | |
xhr.send(options.body); | |
}); | |
export default progressFetch; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const imageUpload = async (uri, onProgress = {}) => { | |
const data = new FormData(); | |
data.append('file', { | |
uri, | |
type: mimetype.lookup(uri), | |
name: 'image', | |
}); | |
const options = { | |
method: 'post', | |
body: data, | |
}; | |
const response = await progressFetch(`https://example.com/img`, options, onProgress).then(res => JSON.parse(res)); | |
if (response.error) { | |
return response; | |
} | |
return response.result; | |
}; | |
export default class App extends React.Component { | |
... | |
onButtonPress = async (e) => { | |
const { status } = await Permissions.askAsync(Permissions.CAMERA_ROLL); | |
if (status === 'granted') { | |
const result = await ImagePicker.launchImageLibraryAsync({ | |
allowsEditing: true, | |
aspect: [1, 1], | |
}); | |
if (!result.cancelled) { | |
const response = await imageUpload(result.uri, (progress) => { | |
console.log(progress) | |
}); | |
if (!response.error) { | |
this.setState({ img: response.url }); | |
} else { | |
Alert.alert('エラー', '画像のアップロードができませんでした'); | |
} | |
} | |
} else { | |
Alert.alert('Permission Error', 'カメラロールの読み取り許可がありません'); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment