这篇文章给大家分享的是有关在HTML5中怎么解决图片上传预处理问题的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

获取图片

通过 File API 获取图片。

varinput=document.createElement('input');input.type='file';input.addEventListener('change',function(){varfile=this.files[0];});input.click();

预览图片

使用 createObjectURL() 或者 FileReader 预览图片:

varimg=document.createElement('img');img.src=window.URL.createObjectURL(file);varimg=document.createElement("img");varreader=newFileReader();reader.onload=function(e){img.src=e.target.result;}reader.readAsDataURL(file);

使用 canvas 做缩略图

varcanvas=document.createElement("canvas");varctx=canvas.getContext("2d");varMAX_WIDTH=800;varMAX_HEIGHT=600;varwidth=img.width;varheight=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){varform=newFormData();form.append('file',blob);fetch('/api/upload',{method:'POST',body:form});});

感谢各位的阅读!关于“在HTML5中怎么解决图片上传预处理问题”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!