重点
post请求,提交的参数数据较大,将参数放入body中,格式为FormData
const formData = new FormData();
prns.forEach(i => {
formData.append('prns', i);
})
let request = new HttpRequest("POST", this.url, formData, {
headers: this.jwt(),
responseType: "blob",
reportProgress: true
})
文件上传
isUploading: Boolean = false;
customReq = (item: UploadXHRArgs) => {
const formData = new FormData();
if (this.fileList.length == 0) {
this.message.error('请上传tif文件!');
return;
}
formData.append('files', this.fileList[0]);
const req = new HttpRequest('POST', this.url, formData, {});
this.isUploading = true;
return this.http.request(req).pipe(filter(e => e instanceof HttpResponse)).subscribe((raster: HttpResponse<any>) => {
this.isUploading = false;
if (raster.status == 201) {
this.message.success('文件上传成功!');
this.fileList = [];
this.filesDisabled = this.fileList.length == 1;
} else {
this.message.error('文件上传失败!');
}
}, () => {
this.message.error('文件上传失败!');
this.isUploading = false;
})
};
文件下载
<button nz-button nzType="primary" (click)="partDownload()">批量下载</button>
<nz-spin [nzSpinning]="isSearch || isDownload" [nzIndicator]="indicatorTemplate">
<yz-ngx-grid #grid [settings]="settings" [source]="source" (onBaGridReady)="onBaGridReady($event)">
</yz-ngx-grid>
</nz-spin>
<ng-template #indicatorTemplate>
<div style="width: 100%;height:100%;background-color: rgba(255,255,255,0.6);">
<i nz-icon nzType="loading" style="font-size: 72px;"></i><br><br><br>
<ng-container *ngIf="isDownload">
<div style="width: calc(100% - 150px);">
<nz-progress [nzPercent]="progress" [nzStrokeWidth]="20" [nzStrokeColor]="'#32b16c'"
[nzFormat]="format">
</nz-progress>
</div>
</ng-container>
</div>
</ng-template>
import { Component, Input, OnInit, ViewChild } from '@angular/core';
import { YzNgxGridComponent } from '@yz/ui';
import { NzMessageService } from 'ng-zorro-antd';
import { ApiService } from '../../services/api.service';
import { ProductCod, DataDownloadService } from '../../services/data-download.service';
import { ProductService } from '../../services/product.service';
@Component({
selector: 'app-data-download',
templateUrl: './data-download.component.html',
styleUrls: ['./data-download.component.scss']
})
export class DataDownloadComponent implements OnInit {
reso = "1KM";
productType: string = 'NPP-Monthly';
isSearch: boolean = false;
isDownload: boolean = false;
public powerData: Array<ProductCod> = [];
@ViewChild("grid", { static: false }) grid: YzNgxGridComponent;
public source = [];
public gridOptions = null;
public settings = [
{
headerName: '序号',
field: "id",
width: 180,
sort: 'asc',
checkboxSelection: true,
headerCheckboxSelection: true,
},
{
headerName: '文件名称',
field: "filename",
width: 900,
cellRenderer: (params) => {
let div = document.createElement("div");
div.textContent = params.value;
div.title = params.value
return div;
},
},
{
headerName: '时段',
field: "productDate",
},
{
headerName: '格式',
field: "dataFormat",
width: 100,
},
{
headerName: '分辨率',
field: "resolution",
width: 130,
},
{
headerName: '文件大小(MB)',
field: "size",
},
{
headerName: '操作',
width: 100,
cellRenderer: "customComponent",
cellRendererParams: [
{
value: '下载',
callBackFunction: (data) => this.download([data])
}
]
}
]
constructor(
public apiService: ApiService,
private message: NzMessageService,
public dataDownloadService: DataDownloadService,
public productService: ProductService) {
}
ngOnInit() {
this.search();
}
search() {
this.isSearch = true;
this.dataDownloadService.queryDownloadData()
.subscribe(data => {
this.source = [];
let source = [];
this.isSearch = false;
if (data.length <= 0) {
this.message.warning('产品查询失败')
return;
}
data.forEach((prns, index) => {
let item: GridDataInfo = new GridDataInfo();
item.id = index + 1;
item.filename = prns[0];
item.productDate = `${prns[0].split('_')[4].substring(0, 4)}年${Number(prns[0].split('_')[4].substring(4, 6))}月`;
item.dataFormat = 'img';
item.resolution = '1KM';
item.size = (prns[1] / 1024 / 1024).toFixed(2);
source.push(item)
})
this.source = source
}, e => {
this.message.error('产品信息查询失败')
return
})
}
progress: number = 0;
format = (percent: number) => `正在下载数据:${percent} %`;
download(d: Array<GridDataInfo>) {
console.log(d);
this.progress = 0;
this.isDownload = true;
let data: Array<string> = []
d.forEach(info => {
data.push(info.filename)
})
this.dataDownloadService.download(data, 'province:pac=320000').subscribe((event) => {
this.progress = Math.round(event.loaded / event.total * 10000) / 100;
}, (error) => {
this.message.warning('下载出现异常');
this.isDownload = false;
}, () => {
setTimeout(() => {
this.isDownload = false;
}, 1000)
})
}
partDownload() {
let rows = this.gridOptions.api.getSelectedRows();
if (rows.length > 10) {
this.message.error('一次批量下载,最多选择10个产品');
return;
} else if (rows.length == 0) {
this.message.warning('请勾选要下载的产品');
return;
}
this.download(rows);
}
onBaGridReady(params) {
this.gridOptions = params;
params.api.sizeColumnsToFit();
}
}
export class GridDataInfo {
id: number;
filename: string;
productDate: string;
dataFormat: string;
resolution: string;
size: string;
}
service.ts
import { HttpClient, HttpEventType, HttpRequest } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
import { ErrorHandler } from '../model/error-handler';
import { ApiService } from './api.service';
import { AppConfig } from './app.config';
@Injectable({
providedIn: 'root'
})
export class DataDownloadService extends ApiService {
private downloadProgress: Subject<{ loaded: number, total: number }>;
private url: any;
constructor(http: HttpClient, private appConfig: AppConfig, private errorHandler: ErrorHandler) {
super(http);
this.url = this.appConfig.sysConfig.js_url;
}
download(prns: Array<string>, where?: string) {
const formData = new FormData();
prns.forEach(i => {
formData.append('prns', i);
})
let request = new HttpRequest("POST", `${this.url}/download/${where ? '?where=' + where : ''}`, formData, {
headers: this.jwt(),
responseType: "blob",
reportProgress: true
})
this.downloadProgress = new Subject<{ loaded: number, total: number }>();
this.http.request(request).subscribe(event => {
if (event.type === HttpEventType.DownloadProgress) {
this.downloadProgress.next({
loaded: event.loaded,
total: event.total
})
}
if (event.type === HttpEventType.Response) {
this.downloadExportFile(event.body, prns.length == 1 ? prns[0].split('.')[0] + 'tif' : `${new Date().getTime()}.zip`);
this.downloadProgress.complete();
}
}, error => {
this.downloadProgress.error(error);
})
return this.downloadProgress;
}
public downloadExportFile(blob: any, fileName: string) {
let downloadElement = document.createElement('a');
let href = blob;
downloadElement.target = '_blank';
if (typeof blob == 'string') {
downloadElement.target = '_blank';
} else {
href = window.URL.createObjectURL(blob);
}
downloadElement.href = href;
downloadElement.download = fileName;
document.body.appendChild(downloadElement);
downloadElement.click();
document.body.removeChild(downloadElement);
if (typeof blob != 'string') {
window.URL.revokeObjectURL(href);
}
}
}
export class ProductCod {
username: string;
productId: string;
whereStr: string;
id: string;
url: string;
template: string;
startDate: string;
endDate: string;
resolution: string;
dateArr: string[];
}