通过 File API
获取图片
var input = document.createElement('input');
input.type = 'file';
input.addEventListener('change', function(){
var file = this.file[0];
})
input.click();
使用 createObjectURL()
或者 FileReader
预览图片
var img = document.createElement('img');
img.src = window.URL.createObjectURL(file);
var img = document.createElement('img');
var reader = new FileReader();
reader.onLoad = function(e){
img.src = e.target.result;
}
reader.readAsDataURL(file);
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var MAX_WIDTH = 800;
var MAX_HEIGHT = 600;
var width = img.width;
var height = img.height;
if(width > height){
if(width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
} else {
if(height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT;
}
}
canvas.width = width;
canvas.height = height;
ctx.drawImage(img, 0, 0, width, height)
canvas.toBlob(function(blob){
var form = new FormData();
form.append('file',blob);
fetch('api/upload', {method: 'POST', body: form});
})