我在Google Chrome中遇到了下载问题.
我使用的是 Ruby 2.2,Rails 4.2,AngularJS 1.2.
我使用的是 Ruby 2.2,Rails 4.2,AngularJS 1.2.
我们这里没有数据库.我们通过API获得的一切.我们试图下载的文件大约是7 MB.它给我们“失败:网络错误”.虽然它在Firefox上运行良好.
从API我们获得JSON中的二进制数据.我们正在解析它.然后:
send_data response_fields["attachment"],type: response_fields["mimeType"],disposition: 'attachment',filename: params[:filename]
当我们使用AngularJS时,我们在AngularJS Controller中捕获该值,然后将其转换为:
var str = data; var uri = "data:" + mimeType + ";base64," + str; var downloadLink = document.createElement("a"); downloadLink.href = uri; downloadLink.download = filename; document.body.appendChild(downloadLink); downloadLink.click(); document.body.removeChild(downloadLink);
这适用于Firefox&甚至Chrome也可以缩小文件大小.不知道为什么它会在Chrome上为更大的尺寸提供错误.
有什么建议?
谢谢.
解决方法
这几乎与这些问题
1和
2重复,但由于它们特别处理canvas元素,我将在这里重写一个更全局的解决方案.
此问题是由于在锚点(< a>)下载属性中设置了大小限制.我不太确定他们为什么这样做,但解决方案很简单.
将dataURI转换为Blob,然后从此Blob创建ObjectURL,并将此ObjectURL作为锚点的下载属性传递.
// edited from https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob#Polyfill function dataURIToBlob(dataURI) { var binStr = atob(dataURI.split(',')[1]),len = binStr.length,arr = new Uint8Array(len),mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0] for (var i = 0; i < len; i++) { arr[i] = binStr.charCodeAt(i); } return new Blob([arr],{ type: mimeString }); } var dataURI_DL = function() { var dataURI = this.result; var blob = dataURIToBlob(dataURI); var url = URL.createObjectURL(blob); var blobAnchor = document.getElementById('blob'); var dataURIAnchor = document.getElementById('dataURI'); blobAnchor.download = dataURIAnchor.download = 'yourFile.mp4'; blobAnchor.href = url; dataURIAnchor.href = dataURI; stat_.textContent = ''; blobAnchor.onclick = function() { requestAnimationFrame(function() { URL.revokeObjectURL(url); }) }; }; // That may seem stupid,but for the sake of the example,we'll first convert a blob to a dataURI... var start = function() { stat_.textContent = 'Please wait while loading...'; var xhr = new XMLHttpRequest(); xhr.responseType = 'blob'; xhr.onload = function() { status.textContent = 'converting'; var fr = new FileReader(); fr.onload = dataURI_DL; fr.readAsDataURL(this.response); }; xhr.open('GET','https://dl.dropBoxusercontent.com/s/bch2j17v6ny4ako/movie720p.mp4?dl=0'); xhr.send(); confirm_btn.parentNode.removeChild(confirm_btn); }; confirm_btn.onclick = start;
<button id="confirm_btn">Start the loading of this 45Mb video</button> <span id="stat_"></span> <br> <a id="blob">blob</a> <a id="dataURI">dataURI</a>
还有一个jsfiddle version for FF,因为他们不允许从stack-snippets下载内容…