HTML5可以下载的,不需要后端,纯前端支持。HTML5的一个例子:
var content = "file content!";
var data = new Blob([content],{type:"text/plain;charset=UTF-8"});
var downloadUrl = window.URL.createObjectURL(data);
var anchor = document.createElement("a");
anchor.href = downloadUrl;
anchor.download = "文件名.txt";
anchor.click();
window.URL.revokeObjectURL(data);
//文件下载
var blob = new Blob([要保存的文件流], { type: 'application/octet-stream' }),
fileName = 'filename' + path.substring(path.lastIndexOf("."), path.length);
////filename,摘取了常用的部分,其实还有其他一些mimetypes = array(
//// 'doc' => 'application/msword',
//// 'bin' => 'application/octet-stream',
//// 'exe' => 'application/octet-stream',
//// 'so' => 'application/octet-stream',
//// 'dll' => 'application/octet-stream',
//// 'pdf' => 'application/pdf',
//// 'ai' => 'application/postscript',
//// 'xls' => 'application/vnd.ms-excel',
//// 'ppt' => 'application/vnd.ms-powerpoint',
//// 'dir' => 'application/x-director',
//// 'js' => 'application/x-javascript',
//// 'swf' => 'application/x-shockwave-flash',
//// 'xhtml' => 'application/xhtml+xml',
//// 'xht' => 'application/xhtml+xml',
//// 'zip' => 'application/zip',
//// 'mid' => 'audio/midi',
//// 'midi' => 'audio/midi',
//// 'mp3' => 'audio/mpeg',
//// 'rm' => 'audio/x-pn-realaudio',
//// 'rpm' => 'audio/x-pn-realaudio-plugin',
//// 'wav' => 'audio/x-wav',
//// 'bmp' => 'image/bmp',
//// 'gif' => 'image/gif',
//// 'jpeg' => 'image/jpeg',
//// 'jpg' => 'image/jpeg',
//// 'png' => 'image/png',
//// 'css' => 'text/css',
//// 'html' => 'text/html',
//// 'htm' => 'text/html',
//// 'txt' => 'text/plain',
//// 'xsl' => 'text/xml',
//// 'xml' => 'text/xml',
//// 'mpeg' => 'video/mpeg',
//// 'mpg' => 'video/mpeg',
//// 'avi' => 'video/x-msvideo',
//// 'movie' => 'video/x-sgi-movie',
////);
downFile(blob, fileName);
//js下载文件流
function downFile(blob, fileName) {
if (window.navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(blob, fileName);
} else {
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = fileName;
link.click();
window.URL.revokeObjectURL(link.href);
}
}
因为只是简单html页面,没有后台代码。想通过jquery的函数将返回的json数据内的一个二进制数组保存为文件。
HTML5可以下载的,不需要后端,纯前端支持。HTML5的一个例子:
var content = "file content!";
var data = new Blob([content],{type:"text/plain;charset=UTF-8"});
var downloadUrl = window.URL.createObjectURL(data);
var anchor = document.createElement("a");
anchor.href = downloadUrl;
anchor.download = "文件名.txt";
anchor.click();
window.URL.revokeObjectURL(data);
通过json获得的二进制,应该不是实际意义上的二进制吧?
json中的数组不是TypedArray,需要转化一下。
var binaryData = [0,0,1,1,1,0,0,0,1,1]; //普通数组
//要保存的数据是10个二进制位,但是一个字节是8位,so,需要16位,2个字节
var binLen = binaryData.length;
var byteLen = Math.ceil(binLen/8);
var buffer = new ArrayBuffer(byteLen ); // 开辟两个字节的缓冲区
var byteData = new Uint8Array(buffer);
for(var i=0; i=0&&j
Blob+ArrayBuffer+URL.createObjectURL+anchor.click,一系列特性,完成了无需后端的文件下载。