Skip to content

Instantly share code, notes, and snippets.

@earlgreyxxx
Last active Sep 13, 2021
Embed
What would you like to do?
/******************************************************************************
file name : index.js
画像を縮小して ajax でアップロードする。
usage :
<input type="file" name="sample" accept="image/png,image/jpeg">
<script type="module" src="index.js"></script>
******************************************************************************/
import ResizeImage from './resize.image.js';
(function($) {
$(function() {
$('input[type=file]').change(async function() {
if(this.files.length < 1)
return;
let file = this.files[0];
let filename = file.name;
// parameter
let limit_mb = 15; // MB
let limit = limit_mb * 1024 * 1024;
let threshold = 1500; // Pixcels
if(!file.type.match(/image\/(?:jpe?g|png)/))
return window.alert('mime type is not image/png or image/jpeg');
if(file.size > limit)
return window.alert('Image file size is too larage. Limit is ' + limit_mb.toString() + 'MB.');
// go to resize!
if(!(file = await ResizeImage(file,threshold)))
return;
/// upload by ajax
let fd = new FormData();
fd.append($(this).attr('name'), file);
// change url if try this code on.
$.ajax({
url: 'uploader.php',
type: 'POST',
dataType: 'json',
data: fd,
processData: false,
contentType: false
})
.fail(function() {
alert('通信エラーもしくはサーバーがエラーを返しました');
})
.always(function(json) {
alert(json.message);
if(json.success)
location.href = json.uploadfile;
});
});
})
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment