美文网首页
关于图片的上传,base64 和blob的上传

关于图片的上传,base64 和blob的上传

作者: nzjcnjzx | 来源:发表于2019-08-09 16:48 被阅读0次
    • 图片转base64 base64 转blob
    • 关于 processData: false,
      contentType: false,

    processData 要求为Boolean类型的参数,默认为true。默认情况下,发送的数据将被转换为对象(从技术角度来讲并非字符串)以配合默认内容类型"application/x-www-form-urlencoded"。如果要发送DOM树信息或者其他不希望转换的信息,请设置为false
    比如var formData = new FormData();
    formData.append("xxx","xxxx");
    异步发送这个数据的时候必须设置processData:false

    contentType:“application/json” 必须是json数据, 注意 name:"xxx" 这个不是json串 ,所以不可以设置contentType 让他默认即可

    在 ajax 中 contentType 设置为 false 是为了避免 JQuery 对其操作,从而失去分界符,而使服务器不能正常解析文件。


    image.png
    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
        <style>
            #pre-img {
                width: 100px;
                height: 100px;
            }
        </style>
    </head>
    
    <body>
        <form id="uploadForm" enctype="multipart/form-data">
            文件:<input id="file" type="file" name="file" />
        </form>
        <button id="btn">使用二进制上传图片</button>
        <button id="btn1">使用base64上传</button>
        <img id="pre-img" src="" alt="">
    </body>
    
    </html>
    <script src="./jquery.min.js"></script>
    <script>
        var img =
            'data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUgAAACIAAAAiCAYAAAA6RwvCAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAyUSURBVFhHNZh5cF5lFcbfu3z7ly9J01alMjquhdKmSdPFVhwZpMqgDlpRKK0oda2FQhfaNGmz70mzf1mapQ1USmHGwf9wnxEV1FFnHJhRoPuS7vuGzjz zpf6xzv3fvfmvuc55zznOeeN67zg1HHeqe2sr9YzgVpO271T70Vf2UuBsudj6j2bUOMxp9oTTjXnfG067utbvwu0tDfUBx7zlFrq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aryQYZCAhhm2WMO8bSU8jIbSZw4jVfzlEC/yckSzGc chjO/m jyR3HczkvPatMLUNec1o I4zo1dZzTkG5N1m133kNJ9gHMP7ElpNQenteS AnKactZAxBom Rq8r2HQqblAawdIE4C62bCf8S5rsyYbDbHpLgzu5vri 4Fe W8M4sZR0ghDOQb5bidgeiH98GUOU3xng7otc2CCb166FZH7xptOT3IAWkdJlptUwwMTqkoDhlxvRic2o5iV3FtfyXkCkYc4ggwbJywS8OGFGx4gQr38nyiRwSDvO3DERLCdFHTS/LoZHS21NsGbuo5QOeNEZOJWKLf6HccJPaaNNDMTLusZdWhFxYkwd0Zde4Buy7Wcs2sN73rsUERajJCmFRN4tQcweyGrgdhr8s4h3ib2VjiVG4pIZ4el9v/AiGAXa/AaR9vrHC/gkPvxUbwmGtWAqOXDhrMhHEkABEGzEzyH5k1IfC0tvY3Bx4AYL0wTDIhJ9YvI Ut4tf/9KMQzgnKcxKB1YANi1WXqac/sXyBdNoNw7YfAfaTZisJtZKyrJg2teGv/HrDTeTMRKWcWfYYqepqI2b2d/noBYR9bR7W sQfh2gsIWybXe0nPKJ72GNkB0WYgiJ6B7za94Ld538Oyad70wyqwnXu3jUg0IdMd5L8bZIauEWDlh502kpItR3yG3zC3manlLlhvXdTUc8KAWPMiPcYRK91BNu4FiP3PpYv09dmRAcN9GDOJH0H0bFw0jtjAZKTtvODpf58FEmz EY77AAAAAElFTkSuQmCC'
        // var formData = new FormData($('#uploadForm')[0]);
    
        btn1.onclick = function () {
            uploadFile(1);
        }
        btn.onclick = function () {
            uploadFile(2);
        }
    
        function uploadFile(type) {
            var file = document.getElementById('file');
            var formData = new FormData();
            var url = URL.createObjectURL(file.files[0]);
            getImgBase64(url, function (img) {
                $('#pre-img').attr('src', img);
                // formData.append('FileContent', img);
                // formData.append("FileContent", file.files[0]);
                var fileImg = type === 1 ? img : dataURItoBlob(img);
                formData.append("FileContent", fileImg);
                var filePathArr =file.value.split('\\');
                var fileName = filePathArr[filePathArr.length - 1];
                console.log(dataURItoBlob(img))
                formData.append("FILEPURPOSE", 'A');
                formData.append("FileName", fileName);
                formData.append("System", 'SMARTMRO');
                formData.append("Module", 'ITEMMASTER');
                formData.append("cuser", 'admin');
                formData.append("Rno", 'IM20190809063');
                $.ajax({
                    type: "post",
                    headers: {
                        Authorization: 'Bearer'
                    },
                    url: '/api/IMPRCS001/Upload',
                    data: formData,
                    cache: false,
                    processData: false,
                    contentType: false,
                    success: function (res) {
                        console.log(res)
                    }
                })
            })
        }
    
        function image2Base64(img) {
            var canvas = document.createElement("canvas");
            canvas.width = img.width;
            canvas.height = img.height;
            var ctx = canvas.getContext("2d");
            ctx.drawImage(img, 0, 0, img.width, img.height);
            var dataURL = canvas.toDataURL("image/png");
            return dataURL;
        }
    
        function getImgBase64(src, cb) {
            var base64 = "";
            var img = new Image();
            img.src = src;
            img.onload = function () {
                base64 = image2Base64(img);
                cb && cb(base64);
            }
        }
    
        function dataURItoBlob(base64Data) {
            var byteString
            if (base64Data.split(',')[0].indexOf('base64') >= 0) {
                byteString = atob(base64Data.split(',')[1])
            } else byteString = unescape(base64Data.split(',')[1])
            var mimeString = base64Data
                .split(',')[0]
                .split(':')[1]
                .split(';')[0]
            var ia = new Uint8Array(byteString.length)
            for (var i = 0; i < byteString.length; i++) {
                ia[i] = byteString.charCodeAt(i)
            }
            return new Blob([ia], {
                type: mimeString
            })
        }
    </script>
    
    • 使用原生ajax上传
      var xhr = new XMLHttpRequest();
                 xhr.open('post','/api/IMPRCS001/Upload');
                 xhr.setRequestHeader('Authorization', 'Bearer');
                 xhr.onreadystatechange = function(){
                     if(xhr.readyState === 4&&xhr.status ===200){
                         console.log(JSON.parse(xhr.responseText))
                     }
                 }
                 xhr.send(formData);
    

    相关文章

      网友评论

          本文标题:关于图片的上传,base64 和blob的上传

          本文链接:https://www.haomeiwen.com/subject/uabhjctx.html