preface

In the work, often encounter pictures or files click to download the front-end requirements. However, there may be a case where a click on an image download turns into an online preview instead of an image download. The following solution is the one I have practiced (Vue project). Note and give some ideas to those who need them.

1. Under normal circumstances, click “A” to download

</a>Copy the code

This approach will most likely result in images being previewed online rather than downloaded locally; So use the following two ways to solve;

2. A tag image url with filename parameter (applicable for same-origin)

Download () {let url = 'image path? Filename = filename with suffix '; let a = document.createElement('a'); a.href = url; A.download = 'custom file name '; }Copy the code

The url containing filename is resolved as follows: 1. The filename cannot be modified. 2. Preview instead of downloading when the file is an image.

3. Use the following methods when the download fails due to cross-domain problems

DownloadImage () {let url = 'image URL '; let urlList = url.split('.'); let suffix = urlList[urlList.length - 1]; Let a = document.createElement('a'); document.body.appendChild(a); A.ownload = 'image name '; a.target = '_blank'; this.getUrlBase64(url, base64 => { a.setAttribute('href', base64); a.click(); a = null; }, suffix); } getUrlBase64(url, callback, suffix) { let canvas = document.createElement('canvas'); let ctx = canvas.getContext('2d'); let img = new Image(); img.src = url; img.crossOrigin = ''; Img. Onload = () => {canvas. Height = img.height; canvas.width = img.width; ctx.drawImage(img, 0, 0); let dataURL = canvas.toDataURL(`image/${suffix}`); callback.call(this, dataURL); canvas = null; }; }Copy the code

conclusion

The above method can be used to solve the problem of downloading pictures. If there is a better way to solve the problem, please communicate. Progress together! thank you