文件上传、下载(post)

12 篇文章 0 订阅
7 篇文章 0 订阅

重点

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, //列头设置复选框
      // rowSelection: 'multiple',
    },
    {
      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;//四舍五入2位小数

    }, (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) {
    // console.log(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); //释放掉blob对象
    }
  }
}

export class ProductCod {
  username: string;
  productId: string;
  whereStr: string;
  id: string;
  url: string;
  template: string;
  startDate: string;
  endDate: string;
  resolution: string;
  dateArr: string[];
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值