Javascript:上传之前先压缩图像文件,如何将压缩文件设置为dom元素?

时间:2019-11-30 13:25:03

标签: javascript file upload compression

如下面的代码,我想在上传到服务器之前先压缩图像文件,所以我使用下面的代码,我的问题是如何将压缩文件分配给html中定义的dom元素“ file”? 非常感谢您的帮助~~

HTML:
    <div class="form-group">
        <label for="label_name">do not exceed 5M</label>
        <input type="file" class="form-control" id="file" name="file" multiple class="file-loading">
    </div>

Script:
<script>
     document.getElementById('file').addEventListener('change',function (e) {

        let fileObj = e.target.files[0]

        compressFile(fileObj,function (file_output) {

            //now the file was compressed, in below code, I want to set it to HTML element "file" defined above, so I want to create an object flist as below
            let list = new DataTransfer();
            let file = new File(???);  //what should I do to set the object file_output to File?
            list.items.add(file);
            let flist = list.files;

            $("#file")[0].files = flist;  //here I want to set the compressed file to #file and submit the form later, but it seems does not work.

            //document.getElementById('file') = files;

        })

    })


    function compressFile(file,callback) {
        let fileObj = file;
        let reader = new FileReader()
        reader.readAsDataURL(fileObj) 
        reader.onload = function(e) {
             let image = new Image()
            image.src = e.target.result
            image.onload = function () {
                let canvas = document.createElement('canvas'),
                    context = canvas.getContext('2d'),
                    imageWidth = image.width / 4,   
                    imageHeight = image.height / 4,
                    data = ''
                canvas.width = imageWidth
                canvas.height = imageHeight
                context.drawImage(image, 0, 0, imageWidth, imageHeight)
                data = canvas.toDataURL('image/jpeg')
                let arr = data.split(','), mime = arr[0].match(/:(.*?);/)[1], 
                    bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
                while (n--) {
                    u8arr[n] = bstr.charCodeAt(n);
                }
                let output_file = new window.File([new Blob([u8arr], {type: mime})], file.name, {type: 'image/jpeg'})
                callback(output_file) 
            }
        }
    }
</script>

0 个答案:

没有答案
相关问题