As below code, I want to compress image file before upload to server, so I'm using the code below, my question is how should I assign the compressed file to the dom element "file" which defined in html?
(如下面的代码,我想在上传到服务器之前先压缩图像文件,所以我使用下面的代码,我的问题是我应该如何将压缩文件分配给html中定义的dom元素“ file”?)
Thanks very much for help~~(非常感谢您的帮助~~)
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>
ask by jameslai-stackoverflow translate from so
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…