[js] js downloads files to local according to url or data

In the past, you can directly use windows.location.href and add a download to the label,

Later, I found that the Apple browser could not download it like this, but instead opened the file directly in the browser.

The solution is as follows

(1) If the data of the file is returned from the background, then directly import this js into the front file , and then directly call the following method. Click here for the js download address , which are data, file name, file format, and common file formats. See the end of this article

download(data, strFileName, strMimeType);

(2) If only one url is returned in the background, then first refer to the js just downloaded, and then use the following code to get the data and download it. Right now

// 下载含有url的文件
function downloadUrlFile(url, fileName) {
	const url2 = url.replace(/\\/g, '/');
	const xhr = new XMLHttpRequest();
	xhr.open('GET', url2, true);
	xhr.responseType = 'blob';
	//如果希望文件名就是url斜杠最后的部分,则加上下面两行代码,fileName参数传url就行
	//var index = fileName .lastIndexOf("\/");
	//fileName  = fileName .substring(index + 1, fileName .length);
	// 为了避免大文件影响用户体验,建议加loading
	xhr.onload = () => {
		if (xhr.status === 200) {
			// 获取文件blob数据并保存
			download(xhr.response, fileName, "text/csv" );
		}
	};
	xhr.send();
}

(3) The common file format I saw in the blog posts of other bloggers

https://blog.csdn.net/zhuyu19911016520/article/details/88714289

Guess you like

Origin blog.csdn.net/mudarn/article/details/118547480