import base64ToBlob from './base64ToBlob';
import { RE_BASE64 } from './consts';

/**
 * 下载文件到本地，并指定文件名
 * @param {File|Blob|string} source Base64或dataURI数据
 * @param {*} fileName 下载文件名
 */
function downloadFile(source, fileName) {
  if (RE_BASE64.test(source)) {
    source = base64ToBlob(source);
  }

  if (source instanceof Blob) {
    var aLink = document.createElement('a');
    var event = document.createEvent('HTMLEvents');
    event.initEvent('click', true, true);
    aLink.download = fileName;
    aLink.href = URL.createObjectURL(source);
    aLink.click();
  }
}

export default downloadFile;
