1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > html实现图片上传到浏览器并显示

html实现图片上传到浏览器并显示

时间:2019-01-06 19:32:31

相关推荐

html实现图片上传到浏览器并显示

方法一

利用原生js实现图片上传

上传文件时,需要设置请求头,一般请求头是json格式,一般文件的请求数据是formdata类型,所以需要设置请求头Content-Type:multipart/form-data;charest=UTF-8

html

<div class="div_model"><img id="cropedBigImg0" src="images/0.png" class="div_model_img"/><input type="file"class="file" accept="image/gif,image/jpeg, image/png, image/jpg"id="chooseImage0"></div>

js

//图片上传到浏览器并显示function ProcessFile(e) {var file = document.getElementById('chooseImage0').files[0];console.log(file);var reader = new FileReader();if (file) {reader.onload = function (event) {var txt = event.target.result;$("#cropedBigImg0").attr('src', txt);//将图片base64字符串赋值给img的src//console.log(txt)//base64};}reader.readAsDataURL(file);}function contentLoaded() {document.getElementById('chooseImage0').addEventListener('change',ProcessFile, false);}// var model=document.getElementById('model');// var input=model.querySelectorAll('input');window.addEventListener("DOMContentLoaded", contentLoaded, false);

方法二

利用外部框架layui实现图片上传,

layui在此可以不需要调用layui的css样式,引用上传图片的功能只需要引用layui.js即可,注意引用layui.js最好是本地引用

js

layui.use('upload', function(){var $ = layui.jquery,upload = layui.upload;//普通图片上传var uploadInst = upload.render({elem: '#chooseImage0',url: '/upload/',before: function(obj){//预读本地文件示例,不支持ie8obj.preview(function(index, file, result){$('#cropedBigImg0').attr('src', result); //图片链接(base64)});},done: function(res){//如果上传失败if(res.code > 0){return layer.msg('上传失败');}//上传成功},error: function(){}});})

html

<div class="div_model"><img id="cropedBigImg0" src="images/0.png" class="div_model_img"/><input type="file" class="file" accept="image/gif, image/jpeg, image/png,image/jpg" id="chooseImage0"></div>

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。