» » Use front-end Javascript download file

 

Use front-end Javascript download file

Author: bamboo06 on 17-06-2020, 16:43, views: 132

0
There is often a need to export data to Excel during project development, or to download documents. The simplest way to download is to directly request the file address of the server and download the file through the browser http. But in development, due to project requirements, the address of the file you want to download will not be exposed to the user, and authentication is required to allow the download of the file. What should we do at this time?
Use front-end Javascript download file


Application scenario
The file address is not exposed on the public network, and the file cannot be directly downloaded through the file url.

The content of the file to be downloaded may be dynamically generated according to the user's request, such as exporting an Excel data table.

The backend needs authentication to verify the download request submitted by the user.

Implementation process
The front end sends a get/post request, carrying header information (such as a token for authentication), and the back end receives the request. After the authentication is completed, the corresponding file is read, and the file is sent to the browser in the form of a file stream. The browser completes download.

We call this method Blob download.

The Blob object represents an immutable, raw data file-like object. Blob does not necessarily represent data in javascript native format.

Front-end code
Let's take downloading pictures as an example and use axios to make front-end asynchronous download requests.

In the get method request, we need to carry the token information in the header. This token is your pass in the system. Generally, it is the token given to you by the backend when you log in, which is equivalent to a ticket for the playground. With this For a ticket, you can play any item in the playground, just show the token ticket to the staff when you play.

And also tell the backend that the backend needs to return blob type data, use responseType:'blob'.
axios.get('http://localhost:9998/download.php', {
	headers: {
		'token': '1234512345'
	},
	responseType: 'blob'
}).then((res) => {
	if (res.data.type !== 'application/octet-stream') {
		alert('Download failure.');
		return false;
	}

	const blob = new Blob([res.data], {
		type: 'image/jpeg'
	})

	let a = document.createElement("a");
	let objUrl = URL.createObjectURL(blob);
	a.href = objUrl;
	a.download = 'abc.jpg' //filename
	a.click();
	URL.revokeObjectURL(objUrl); // release memory
	document.body.removeChild(a);
	alert('Download success.');
}).catch((err) => {
	console.log(err);
	alert('Download failure.');
});


After we get the blob object data returned by the backend, create an a tag on the page, and then simulate a click event to save the blob data to a file. Note that URL.createObjectURL(blob) saves the blob in memory, and remember to release the memory after downloading.

Backend code
In the backend download.php, you must first allow the token to be received in the header. If it is a cross-domain request, you should also set the header ("Access-Control-Allow-Origin: *"); to allow cross-domain requests.
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With, token");

$token = isset($_SERVER['HTTP_TOKEN']) ? $_SERVER['HTTP_TOKEN'] : '';
if ($token != '1234512345') {
	echo 'error.';
	exit;
}

$file = '../file/cc.jpg';
if (!file_exists($file)) {
	header('HTTP/1.1 404 Not Found');
	exit;
}

$fileSize = filesize($file); 
//header
header("Content-type: application/octet-stream"); 
header("Accept-Ranges: bytes"); 
header("Accept-Length:".$fileSize);
$fp = fopen($file, "rb"); 
$buffer = 1024; 
$fileCount = 0; 
//send data to browser
while(!feof($fp) && $fileCount < $fileSize){ 
    $cont = fread($fp, $buffer); 
    $fileCount += $buffer; 
    echo $cont; 
}
fclose($fp);


The next step is to verify that the token is correct. The verification process in the above code is pseudo-code. In actual development, the token should be verified according to a certain algorithm according to business needs. The token may contain data such as user information and expiration time.

Then determine whether the file to be downloaded exists. This file may not be in the web directory, and the user cannot directly access it through the url.

The last step is to read the file stream and send it to the browser.

Category: Javascript

Dear visitor, you are browsing our website as Guest.
We strongly recommend you to register and login to view hidden contents.
Information
Comment on the news site is possible only within (days) days from the date of publication.