Skip to content

Instantly share code, notes, and snippets.

@watanabeyu
Last active October 3, 2018 09:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save watanabeyu/1311dd1e9e7317972f266063de7a535d to your computer and use it in GitHub Desktop.
Save watanabeyu/1311dd1e9e7317972f266063de7a535d to your computer and use it in GitHub Desktop.
progress fetch
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;
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