HTML:
<input type="file" name="image" accept="image/*"@change='onUpload'></input>
JS:
toDataURL(file, c, isBase) {
? ? ? ? var reader = new FileReader();
? ? ? ? reader.onload = function () {
? ? ? ? ? ? c(this.result)
? ? ? ? }
? ? ? ? reader.readAsDataURL(file);
? ? },
? ? dealImage:function(path, obj, callback) {
? ? window.pmb=this;
? ? ? ? var img = new Image();
? ? ? ? img.src = path;
? ? ? ? img.onload = function () {
? ? ? ? ? ? var that = this;
? ? ? ? ? ? // 默認(rèn)按比例壓縮
? ? ? ? ? ? var w = that.width,
? ? ? ? ? ? ? ? h = that.height,
? ? ? ? ? ? ? ? scale = w / h;
? ? ? ? ? ? w = obj.width || w;
? ? ? ? ? ? h = obj.height || (w / scale);
? ? ? ? ? ? //生成canvas
? ? ? ? ? ? var canvas = document.createElement('canvas');
? ? ? ? ? ? var ctx = canvas.getContext('2d');
? ? ? ? ? ? // 創(chuàng)建屬性節(jié)點
? ? ? ? ? ? var anw = document.createAttribute("width");
? ? ? ? ? ? anw.nodeValue = w;
? ? ? ? ? ? var anh = document.createAttribute("height");
? ? ? ? ? ? anh.nodeValue = h;
? ? ? ? ? ? canvas.setAttributeNode(anw);
? ? ? ? ? ? canvas.setAttributeNode(anh);
? ? ? ? ? ? ctx.drawImage(that, 0, 0, w, h);
? ? ? ? ? ? canvas.toBlob(function (callback) {
? ? ? ? ? ? console.log("callback",callback);
? ? ? ? ? ? ? ? let formData = new FormData();
? ? ? ? ? ? ? ? formData.append("file", callback);
? ? ? ? ? ? ? ? window.pmb.axios
? ? ? ? ? ? ? ? ? .post(URL, formData, {
? ? ? ? ? ? ? ? ? ? headers: { "Content-Type": "multipart/form-data" }
? ? ? ? ? ? ? ? ? })
? ? ? ? ? ? ? ? ? .then(res => {
? ? ? ? ? ? ? ? ? });?
? ? ? ? ? ? })
? ? ? ? }
? ? },
? ? onUpload(e) {
? ? ? let self=this;
? ? ? self.toDataURL(this.$refs.input.files[0],function(base){
? ? ? ? ? ? self.dealImage(base, {width:400,height:400}, function(blob){
? ? ? ? ? ? ? ? window.open(URL.createObjectURL(blob));
? ? ? ? ? ? });
? ? ? });
? ? },