前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >html上传图片

html上传图片

原创
作者头像
有勇气的牛排
发布2023-06-25 23:18:02
2330
发布2023-06-25 23:18:02
举报
文章被收录于专栏:有勇气的牛排专栏

方案一

代码语言:html
复制
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>头像</title>
</head>

<script src="http://i.gtimg.cn/qzone/biz/gdt/lib/jquery/jquery-2.1.4.js?max_age=31536000"></script>

<script src="js/avator.js"></script>

<body>
<input type="file" id="upLoad" name="image">
<!-- 显示上传之后的图片 -->
<div id='previewImg'>
    <img src="" id='viewImg' style="height: 200px;"/>
</div>
<button id="submit">提交</button>

</body>
</html>
代码语言:javascript
复制
$(function () {
    var imgsrc = ''

    $("#submit").click(function () {
        alert(imgsrc);
        $.ajax({
            url: '/avatar',
            type: 'POST',
            dataType: 'json',
            data: {
                'imgsrc': imgsrc
            },
            success: function (res) {
                alert('666');
            },
            error: function () {
                alert('123');
            }
        });

    });


    $('#upLoad').on('change', function () {
        var filePath = $(this).val(),         //获取到input的value,里面是文件的路径
            fileFormat = filePath.substring(filePath.lastIndexOf(".")).toLowerCase(),
            imgBase64 = '',      //存储图片的imgBase64
            fileObj = document.getElementById('upLoad').files[0]; //上传文件的对象,要这样写才行,用jquery写法获取不到对象

        // 检查是否是图片
        if (!fileFormat.match(/.png|.jpg|.jpeg/)) {
            alert('上传错误,文件格式必须为:png/jpg/jpeg');
            return;
        }

        alert(fileObj.size / 1024);
        if (fileObj.size / 1024 > 20000) {
            // alert('大于200k');
            // 调用函数,对图片进行压缩
            compress(fileObj, function (imgBase64) {
                imgBase64 = imgBase64;    //存储转换的base64编码
                imgsrc = imgBase64;
                $('#viewImg').attr('src', imgBase64); //显示预览图片
            });
        } else {
            // alert('小于200k');
            // 调用函数,不对图片进行压缩
            directTurnIntoBase64(fileObj, function (imgBase64) {
                imgBase64 = imgBase64;    //存储转换的base64编码
                imgsrc = imgBase64;
                $('#viewImg').attr('src', imgBase64); //显示预览图片
            });
        }
    });

    // 不对图片进行压缩,直接转成base64
    function directTurnIntoBase64(fileObj, callback) {
        var r = new FileReader();
        // 转成base64
        r.onload = function () {
            //变成字符串
            imgBase64 = r.result;
            console.log(imgBase64);
            callback(imgBase64);
        }
        r.readAsDataURL(fileObj);    //转成Base64格式
    }

    // 对图片进行压缩
    function compress(fileObj, callback) {
        if (typeof (FileReader) === 'undefined') {
            console.log("当前浏览器内核不支持base64图标压缩");
            //调用上传方式不压缩
            directTurnIntoBase64(fileObj, callback);
        } else {
            try {
                var reader = new FileReader();
                reader.onload = function (e) {
                    var image = $('<img/>');
                    image.load(function () {
                        square = 390,   //定义画布的大小,也就是图片压缩之后的像素
                            canvas = document.createElement('canvas'),
                            context = canvas.getContext('2d'),
                            imageWidth = 0,    //压缩图片的大小
                            imageHeight = 0,
                            offsetX = 0,
                            offsetY = 0,
                            data = '';

                        canvas.width = square;
                        canvas.height = square;
                        context.clearRect(0, 0, square, square);

                        if (this.width > this.height) {
                            imageWidth = Math.round(square * this.width / this.height);
                            imageHeight = square;
                            offsetX = -Math.round((imageWidth - square) / 2);
                        } else {
                            imageHeight = Math.round(square * this.height / this.width);
                            imageWidth = square;
                            offsetY = -Math.round((imageHeight - square) / 2);
                        }
                        context.drawImage(this, offsetX, offsetY, imageWidth, imageHeight);
                        var data = canvas.toDataURL('image/jpeg');
                        //压缩完成执行回调
                        callback(data);
                    });
                    image.attr('src', e.target.result);
                };
                reader.readAsDataURL(fileObj);
            } catch (e) {
                console.log("压缩失败!");
                //调用直接上传方式  不压缩
                directTurnIntoBase64(fileObj, callback);
            }
        }
    }
});

方案2

代码语言:javascript
复制
<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
<input type="file"><br>
<img src="" height="200" alt="Image preview area..." title="preview-img">
<script>
  var fileInput = document.querySelector('input[type=file]'),
          previewImg = document.querySelector('img');
  fileInput.addEventListener('change', function () {
      var file = this.files[0];
      var reader = new FileReader();
      // 监听reader对象的的onload事件,当图片加载完成时,把base64编码賦值给预览图片
      reader.addEventListener("load", function () {
          previewImg.src = reader.result;
      }, false);
      // 调用reader.readAsDataURL()方法,把图片转成base64
      reader.readAsDataURL(file);
  }, false);
</script>
</body>
</html>

参考:

https://www.cnblogs.com/xh_Blog/p/8269581.html

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 方案一
  • 方案2
相关产品与服务
图片处理
图片处理(Image Processing,IP)是由腾讯云数据万象提供的丰富的图片处理服务,广泛应用于腾讯内部各产品。支持对腾讯云对象存储 COS 或第三方源的图片进行处理,提供基础处理能力(图片裁剪、转格式、缩放、打水印等)、图片瘦身能力(Guetzli 压缩、AVIF 转码压缩)、盲水印版权保护能力,同时支持先进的图像 AI 功能(图像增强、图像标签、图像评分、图像修复、商品抠图等),满足多种业务场景下的图片处理需求。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档