Skip to content

文件下载

示例代码

html
<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<script src="./js/jquery-3.6.4.min.js"></script>
		<script src="./js/jweixin-1.3.1.js"></script>
		<script src="./js/angular.min.js"></script>
		<link href="./images/favicon.ico" type="image/x-icon" rel="shortcut icon">
	</head>

	<body ng-app="app" ng-cloak>
		<section ng-controller="ctrl" style="background-color:white;" ng-init="init();">

			<progress class="progress" value="{{ loadedFileSize }}" max="{{ totalFileSize }}"></progress>

			<div ng-click="download()">下载文件</div>
			<div id="iframeBox" style="width: 0px;height: 0px;">
				<!-- <iframe width="100%" height="100%" scrolling="no" src="./file/a.pptx"></iframe> -->
			</div>
		</section>
	</body>

	<script>
		var app = angular.module("app", []);
		app.config(function($locationProvider, $httpProvider) {})
			.controller("ctrl", function($scope, $http, $location, $timeout, $sce) {
				// 这里写逻辑代码
				$scope.loadedFileSize = 0;
				$scope.totalFileSize = 0;

				$scope.init = () => {
					console.log(123);
				}

				// 下载附件
				$scope.download = function() {

					var url = 'http://www.test/a.pdf'; // 预览|下载
					// $('#iframeBox').html('<iframe  width="100%" height="100%" scrolling="no" src="' + url +
					// 	'"></iframe>');
					// return;

					$http.get(url, {
							headers: {
								'Authorization': 'token',
							},
							responseType: 'blob',
							reportProgress: true,
							reportProgress: true,
							eventHandlers: {
								progress: function(c) {
									console.log('Progress -> ' + c);
									console.log(c);

									$scope.loadedFileSize = c.loaded
									$scope.totalFileSize = c.total

								}
							}
						})
						.then(res => {
							console.log(res, 'res');
							// let fileName = x.name;
							let fileName = 'a.pptx';
							var a = document.createElement('a');
							a.download = fileName;
							a.href = URL.createObjectURL(res.data); // blob内容
							console.log(a.href, 'a.href');
							a.click();
							a.remove();
						}).catch(err => {
							const fileReader = new FileReader();
							fileReader.onload = function() {
								try {
									const jsonData = JSON.parse(fileReader.result); // 说明是普通对象数据,后台转换失败
									console.log('后台返回的信息', jsonData);
									alert(jsonData.message)
								} catch (err) { // 解析成对象失败,说明是正常的文件流
									console.log('success...');
								}
							};
							fileReader.readAsText(err.data);
						})
				}
			})
	</script>
</html>