Skip to content

Instantly share code, notes, and snippets.

@nothingrealhappen
Last active May 25, 2016 08:22
Show Gist options
  • Save nothingrealhappen/792c0094a4520aac2988e213d0d067ec to your computer and use it in GitHub Desktop.
Save nothingrealhappen/792c0094a4520aac2988e213d0d067ec to your computer and use it in GitHub Desktop.
Crop avatar before upload to server
// import crop package
import crop from 'crop-image';
// input file onChange callback
this.upload = e => {
const files = e.target.files;
if (files && files[0]) {
const image = new Image();
image.onload = () => {
// crop img first
const { width, height } = image;
const isHoriz = width > height;
const minMax = isHoriz ? [height, width] : [width, height];
const distance = minMax[1] - minMax[0];
const CROP_SIZE = minMax[1] > 500 ? 500 : minMax[1];
const blob = crop(image, isHoriz ? distance : 0, isHoriz ? 0 : distance, minMax[0], minMax[0], CROP_SIZE, CROP_SIZE);
// send blob to server
const f = new FormData();
f.append('user[avatar]', blob, files[0].name);
uploadAvatar(f)
.done(user => {
this.props.dispatch(showSuccessMessage('头像更新成功'));
})
.fail(xhr => showXHRError(xhr, this.props.dispatch));
};
image.src = window.URL.createObjectURL(files[0]);
}
};
// read full commit
// https://github.com/GeekPark/gpk_account/pull/117/commits/1ad250a25e52bc2bd085eebf1177b170ecd44aae
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment