• jquery上传base64位图片


    
    

      <img id="articleImg" width="180" height="100">
      <input type="file" value="上传" id="articleImg


    1
    $('#articleImgBtn').change(function(){ 2 run(this, function (data) { 3 uploadImage(data); 4 }); 5 }); 6 7 function run(input_file, get_data) { 8 /*input_file:文件按钮对象*/ 9 /*get_data: 转换成功后执行的方法*/ 10 if (typeof (FileReader) === 'undefined') { 11 alert("抱歉,你的浏览器不支持 FileReader,不能将图片转换为Base64,请使用现代浏览器操作!"); 12 } else { 13 try { 14 /*图片转Base64 核心代码*/ 15 var file = input_file.files[0]; 16 //这里我们判断下类型如果不是图片就返回 去掉就可以上传任意文件 17 if (!/image/w+/.test(file.type)) { 18 alert("请确保文件为图像类型"); 19 return false; 20 } 21 var reader = new FileReader(); 22 reader.onload = function () { 23 get_data(this.result); 24 } 25 reader.readAsDataURL(file); 26 } catch (e) { 27 alert('图片转Base64出错啦!' + e.toString()) 28 } 29 } 30 } 31 32 function uploadImage(img) { 33 //判断是否有选择上传文件 34 var imgPath = $("#articleImgBtn").val(); 35 if (imgPath == "") { 36 alert("请选择上传图片!"); 37 return; 38 } 39 //判断上传文件的后缀名 40 var strExtension = imgPath.substr(imgPath.lastIndexOf('.') + 1); 41 if (strExtension != 'jpg' && strExtension != 'gif' 42 && strExtension != 'png' && strExtension != 'bmp') { 43 alert("请选择图片文件"); 44 return; 45 } 46 $.ajax({ 47 type: "POST", 48 url: ’上传图片接口‘, 49 data: { token: token,file: img.substr(img.indexOf(',') + 1)}, //视情况将base64的前面字符串data:image/png;base64,删除 50 cache: false, 51 success: function(data) { 52 alert("上传成功"); 53 $("#articleImg").attr('src', JSON.parse(data).imageUrl); 54 }, 55 error: function(XMLHttpRequest, textStatus, errorThrown) { 56 alert("上传失败,请检查网络后重试"); 57 } 58 }); 59 }
  • 相关阅读:
    mac上finalShell的安装
    c 字符串与字符串操作
    .net5 MailKit
    c 99乘法表
    element 动态表单加自定义校验
    遇到的问题 vscode 问题
    vue-element-admin eslint 规则查询表
    利用html2canvas 导出网页 (只是用于自己的笔记,如果需要看配置,自行查找插件api)
    git 常用命令
    uniapp中自动打包微信小程序后自动上传代码
  • 原文地址:https://www.cnblogs.com/cutone/p/6362321.html
Copyright © 2020-2023  润新知