“@angular/common/http”; 从'src/app/services/upload download.service'导入{UploadDownloadService}; 从'src/app/models/ProgressStatus.model'导入{ProgressStatus,ProgressStatusEnum}; @组成部分({ 选择器:“应用程序下载”, templateUrl:'download.component.html' }) 导出类下载组件{ @Input()公共禁用:布尔值; @Input()公共文件名:string; @Output()公共下载状态:EventEmitter; 构造函数(专用服务:UploadDownloadService){ this.downloadStatus=neweventemitter(); } 公开下载(){ this.downloadStatus.emit({status:ProgressStatusEnum.START}); this.service.downloadFile(this.fileName).subscribe( 数据=>{ 开关(数据类型){ 案例HttpEventType.DownloadProgress: this.downloadStatus.emit({status:ProgressStatusEnum.IN_PROGRESS,percentage:Math.round((data.loaded/data.total)*100)}); 打破 案例HttpEventType。响应: this.downloadStatus.emit({status:ProgressStatusEnum.COMPLETE}); const downloadedFile=new Blob([data.body],{type:data.body.type}); 常量a=document.createElement('a'); a、 setAttribute('style','display:none;'); 文件.正文.附件(a); a、 下载=this.fileName; a、 href=URL.createObjectURL(下载文件); a、 目标='u blank'; a、 单击(); 文件.body.removeChild(a); 打破 } }, 错误=>{ this.downloadStatus.emit({status:ProgressStatusEnum.ERROR}); } ); } }
在父组件中添加以下实现: <app-download [disabled]="showProgress" [fileName]="file" (downloadStatus)="downloadStatus($event)"> <p *ngIf="showProgress"> progress {{percentage}}% import { Component, OnInit } from '@angular/core'; import { UploadDownloadService } from 'src/app/services/upload-download.service'; import { ProgressStatusEnum, ProgressStatus } from 'src/app/models/progress-status.model'; @Component({ selector: 'app-filemanager', templateUrl: './file-manager.component.html' }) export class FileManagerComponent implements OnInit { public files: string[]; public fileInDownload: string; public percentage: number; public showProgress: boolean; public showDownloadError: boolean; public showUploadError: boolean; constructor(private service: UploadDownloadService) { } ngOnInit() { this.getFiles(); } private getFiles() { this.service.getFiles().subscribe( data => { this.files = data; } ); } public downloadStatus(event: ProgressStatus) { switch (event.status) { case ProgressStatusEnum.START: this.showDownloadError = false; break; case ProgressStatusEnum.IN_PROGRESS: this.showProgress = true; this.percentage = event.percentage; break; case ProgressStatusEnum.COMPLETE: this.showProgress = false; break; case ProgressStatusEnum.ERROR: this.showProgress = false; this.showDownloadError = true; break; } } }“@angular/common/http”; 从'src/app/services/upload download.service'导入{UploadDownloadService}; 从'src/app/models/ProgressStatus.model'导入{ProgressStatus,ProgressStatusEnum}; @组成部分({ 选择器:“应用程序下载”, templateUrl:'download.component.html' }) 导出类下载组件{ @Input()公共禁用:布尔值; @Input()公共文件名:string; @Output()公共下载状态:EventEmitter; 构造函数(专用服务:UploadDownloadService){ this.downloadStatus=neweventemitter(); } 公开下载(){ this.downloadStatus.emit({status:ProgressStatusEnum.START}); this.service.downloadFile(this.fileName).subscribe( 数据=>{ 开关(数据类型){ 案例HttpEventType.DownloadProgress: this.downloadStatus.emit({status:ProgressStatusEnum.IN_PROGRESS,percentage:Math.round((data.loaded/data.total)*100)}); 打破 案例HttpEventType。响应: this.downloadStatus.emit({status:ProgressStatusEnum.COMPLETE}); const downloadedFile=new Blob([data.body],{type:data.body.type}); 常量a=document.createElement('a'); a、 setAttribute('style','display:none;'); 文件.正文.附件(a); a、 下载=this.fileName; a、 href=URL.createObjectURL(下载文件); a、 目标='u blank'; a、 单击(); 文件.body.removeChild(a); 打破 } }, 错误=>{ this.downloadStatus.emit({status:ProgressStatusEnum.ERROR}); } ); } },angular,typescript,asp.net-core-webapi,Angular,Typescript,Asp.net Core Webapi,在父组件中添加以下实现: <app-download [disabled]="showProgress" [fileName]="file" (downloadStatus)="downloadStatus($event)"> <p *ngIf="showProgress"> progress {{percentage}}% import { Component, OnInit } from '@angular/core'; import { UploadDownlo
进度{{percentage}}%
在父typescript组件中添加以下实现: <app-download [disabled]="showProgress" [fileName]="file" (downloadStatus)="downloadStatus($event)"> <p *ngIf="showProgress"> progress {{percentage}}% import { Component, OnInit } from '@angular/core'; import { UploadDownloadService } from 'src/app/services/upload-download.service'; import { ProgressStatusEnum, ProgressStatus } from 'src/app/models/progress-status.model'; @Component({ selector: 'app-filemanager', templateUrl: './file-manager.component.html' }) export class FileManagerComponent implements OnInit { public files: string[]; public fileInDownload: string; public percentage: number; public showProgress: boolean; public showDownloadError: boolean; public showUploadError: boolean; constructor(private service: UploadDownloadService) { } ngOnInit() { this.getFiles(); } private getFiles() { this.service.getFiles().subscribe( data => { this.files = data; } ); } public downloadStatus(event: ProgressStatus) { switch (event.status) { case ProgressStatusEnum.START: this.showDownloadError = false; break; case ProgressStatusEnum.IN_PROGRESS: this.showProgress = true; this.percentage = event.percentage; break; case ProgressStatusEnum.COMPLETE: this.showProgress = false; break; case ProgressStatusEnum.ERROR: this.showProgress = false; this.showDownloadError = true; break; } } } 从“@angular/core”导入{Component,OnInit}; 从'src/app/services/upload download.service'导入{UploadDownloadService}; 从'src/app/models/progress status.model'导入{ProgressStatusEnum,ProgressStatus}; @组成部分({ 选择器:“应用程序文件管理器”, templateUrl:“./file manager.component.html” }) 导出类FileManagerComponent实现OnInit{ 公共文件:字符串[]; 公共文件下载:字符串; 公众百分比:人数; 公共进程:布尔; public showDownloadError:布尔值; public showUploadError:布尔值; 构造函数(私有服务:UploadDownloadService){} 恩戈尼尼特(){ 这个文件名为.getFiles(); } 私有getFiles(){ 此.service.getFiles().subscribe( 数据=>{ this.files=数据; } ); } 公共下载状态(事件:ProgressStatus){ 开关(事件状态){ 案例ProgressStatusEnum.START: this.showDownloadError=false; 打破 案例进度状态枚举正在进行中: this.showProgress=true; this.percentage=event.percentage; 打破 案例ProgressStatusEnum.COMPLETE: this.showProgress=false; 打破 案例ProgressStatusEnum.ERROR: this.showProgress=false; this.showDownloadError=true; 打破 } } }完成了 我在这个文件中得到一个错误。myFile=files[0];未捕获(承诺中):InvalidStateError:未能设置“HTMLInputElement”的“value”属性:此输入元素接受文件名,该文件名只能通过编程设置为空字符串。Magic!您可以使用
标题()
和选项()。它们是从哪里进口的?有棱角的其他地方?如果有角度,角度在哪里?请给出一个全面的答案。哎呀。我发现这个答案是完成任务的最佳简单方法。嗨,莫莫,谢谢你的解决方案,\u formData显示为空对象。像{}。请建议我如何将文件发送到服务器。returnpost()?真的吗?尝试使用类型script的ResponseContentType.Blob函数它帮助了我:)
...
public uploadFile(fileToUpload: File) {
const _formData = new FormData();
_formData.append('file', fileToUpload, fileToUpload.name);
return<any>post(UrlFileUpload, _formData);
//note: no HttpHeaders passed as 3rd param to POST!
//So no Content-Type constructed manually.
//Angular 4.x-6.x does it automatically.
}
<div class="form-group col-md-6" style="margin-left:50%;margin-top:-8%" >
<input type="file" value="upload" accept=".jpg" (change)=fileUploader($event)>
</div>
public fileUploader(event) {
const elem = event.target;
if (elem.files.length > 0) {
console.log(elem.files[0]);
}
// ...
}
download(row) {
return this.Http
.get(file_path , {
responseType: ResponseContentType.Blob,
})
.map(res => {
return {
filename: row.name,
data: res.blob()
};
})
.subscribe(res => {
let url = window.URL.createObjectURL(res.data);
let a = document.createElement('a');
document.body.appendChild(a);
a.setAttribute('style', 'display: none');
a.href = url;
a.download = res.filename;
a.click();
window.URL.revokeObjectURL(url);
a.remove();
});
}
<div class="col-md-6">
<label class="control-heading">Select File</label>
<input type="file" [multiple]="multiple" #fileInput (change)="selectFile($event)">
<input type="button" style="margin-top: 15px;" [disabled]="!isUploadEditable" class="data-entry-button btn-pink" (click)="uploadFile()" value="Upload" title="{{globalService.generateTooltip('upload attachment','Click to upload document.')}}" data-html="true" data-toggle="tooltip" data-placement="bottom" />
</div>
selectFile(event: any) {
this.selectedFiles = event.target.files;
}
uploadFile() {
this.currentFileUpload = this.selectedFiles.item(0);
this.globalService.pushFileToStorage(this.currentFileUpload).subscribe(event => {
if (event instanceof HttpResponse) {
this.loadDocumentInfo();
this.showNotification('Upload Attachment', 'File Uploaded Successfully', 'success');
this.myInputVariable.nativeElement.value = "";
}
});
this.selectedFiles = undefined;
}
pushFileToStorage(file: File): Observable<HttpEvent<{}>> {
const formdata: FormData = new FormData();
formdata.append('file', file);
formdata.append('documentVersionId', this.documentVersionId.toString());
formdata.append('levelId', this.levelId);
formdata.append('levelKey', this.levelKey);
formdata.append('LoggedInUser', this.loggedInUser);
const req = new HttpRequest('POST', this.urlService.CMMService + '/CMMService-service/UploadFileAsAttachment', formdata, {
reportProgress: true,
responseType: 'text'
}
);
return this.http.request(req);
}
DownloadFile(filePath: string, filename: string) {
this.globalService.DownloadFile(filePath).subscribe(res => {
//console.log('start download:', res);
var url = window.URL.createObjectURL(res);
var a = document.createElement('a');
document.body.appendChild(a);
a.setAttribute('style', 'display: none');
a.href = url;
res.filename = filename;
a.download = res.filename;
a.click();
window.URL.revokeObjectURL(url);
a.remove(); // remove the element
}, error => {
console.log('download error:', JSON.stringify(error));
}, () => {
console.log('Completed file download.')
});
}
public DownloadFile(filePath: string): Observable<any> {
return this.http
.get(this.urlService.CMMService + '/CMMService-service/DownloadFile?filePath=' + filePath, {
responseType: 'blob'
});
}
[HttpGet]
[ODataRoute("DownloadFile")]
public HttpResponseMessage DownloadFile(string filePath)
{
var fileData = CommonDomain.DownloadFileFromS3(filePath);
var dataStream = new MemoryStream(fileData.ByteArray);
HttpResponseMessage httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK);
httpResponseMessage.Content = new StreamContent(dataStream);
httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
httpResponseMessage.Content.Headers.ContentDisposition.FileName = fileData.FileName;
httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
httpResponseMessage.Content.Headers.Add("x-filename", fileData.FileName);
return httpResponseMessage;
}
[HttpGet]
[Route("download")]
public async Task Download([FromQuery] string file) {
var uploads = Path.Combine(_hostingEnvironment.WebRootPath, "uploads");
var filePath = Path.Combine(uploads, file);
if (!System.IO.File.Exists(filePath))
return NotFound();
var memory = new MemoryStream();
using (var stream = new FileStream(filePath, FileMode.Open))
{
await stream.CopyToAsync(memory);
}
memory.Position = 0;
return File(memory, GetContentType(filePath), file);
}
import { Injectable } from '@angular/core';
import { HttpClient, HttpRequest, HttpEvent, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class DownloadService {
private baseApiUrl: string;
private apiDownloadUrl: string;
private apiUploadUrl: string;
private apiFileUrl: string;
constructor(private httpClient: HttpClient) {
this.baseApiUrl = 'http://localhost:5001/api/';
this.apiDownloadUrl = this.baseApiUrl + 'download';
this.apiUploadUrl = this.baseApiUrl + 'upload';
this.apiFileUrl = this.baseApiUrl + 'files';
}
public downloadFile(file: string): Observable> {
return this.httpClient.request(new HttpRequest(
'GET',
`${this.apiDownloadUrl}?file=${file}`,
null,
{
reportProgress: true,
responseType: 'blob'
}));
}
}
export interface ProgressStatus {
status: ProgressStatusEnum;
percentage?: number;
}
export enum ProgressStatusEnum {
START, COMPLETE, IN_PROGRESS, ERROR
}
<button
[disabled]="disabled"
class="button download"
[ngClass]="{'disabled': disabled}"
(click)="download()">download
import { Component, Input, Output, EventEmitter } from '@angular/core';
import { HttpEventType } from '@angular/common/http';
import { UploadDownloadService } from 'src/app/services/upload-download.service';
import { ProgressStatus, ProgressStatusEnum } from 'src/app/models/progress-status.model';
@Component({
selector: 'app-download',
templateUrl: 'download.component.html'
})
export class DownloadComponent {
@Input() public disabled: boolean;
@Input() public fileName: string;
@Output() public downloadStatus: EventEmitter;
constructor(private service: UploadDownloadService) {
this.downloadStatus = new EventEmitter();
}
public download() {
this.downloadStatus.emit( {status: ProgressStatusEnum.START});
this.service.downloadFile(this.fileName).subscribe(
data => {
switch (data.type) {
case HttpEventType.DownloadProgress:
this.downloadStatus.emit( {status: ProgressStatusEnum.IN_PROGRESS, percentage: Math.round((data.loaded / data.total) * 100)});
break;
case HttpEventType.Response:
this.downloadStatus.emit( {status: ProgressStatusEnum.COMPLETE});
const downloadedFile = new Blob([data.body], { type: data.body.type });
const a = document.createElement('a');
a.setAttribute('style', 'display:none;');
document.body.appendChild(a);
a.download = this.fileName;
a.href = URL.createObjectURL(downloadedFile);
a.target = '_blank';
a.click();
document.body.removeChild(a);
break;
}
},
error => {
this.downloadStatus.emit( {status: ProgressStatusEnum.ERROR});
}
);
}
}
<app-download [disabled]="showProgress" [fileName]="file" (downloadStatus)="downloadStatus($event)">
<p *ngIf="showProgress"> progress {{percentage}}%
import { Component, OnInit } from '@angular/core';
import { UploadDownloadService } from 'src/app/services/upload-download.service';
import { ProgressStatusEnum, ProgressStatus } from 'src/app/models/progress-status.model';
@Component({
selector: 'app-filemanager',
templateUrl: './file-manager.component.html'
})
export class FileManagerComponent implements OnInit {
public files: string[];
public fileInDownload: string;
public percentage: number;
public showProgress: boolean;
public showDownloadError: boolean;
public showUploadError: boolean;
constructor(private service: UploadDownloadService) { }
ngOnInit() {
this.getFiles();
}
private getFiles() {
this.service.getFiles().subscribe(
data => {
this.files = data;
}
);
}
public downloadStatus(event: ProgressStatus) {
switch (event.status) {
case ProgressStatusEnum.START:
this.showDownloadError = false;
break;
case ProgressStatusEnum.IN_PROGRESS:
this.showProgress = true;
this.percentage = event.percentage;
break;
case ProgressStatusEnum.COMPLETE:
this.showProgress = false;
break;
case ProgressStatusEnum.ERROR:
this.showProgress = false;
this.showDownloadError = true;
break;
}
}
}