Загрузка и загрузка файла в angular 4 typescript
Как я могу скачать (файл .exe
, который находится в корневом пути) и загрузить файл из Angular 4?.
Я новичок в Angular4, а также в машинописи и .NET Core Web API. Я гуглил по этому поводу, но не смог найти решение.
Вот несколько похожих вопросов, которые я нашел:
Ответы
Ответ 1
Я хотел бы добавить обновление для Angular 4.3/5/6/7/8, особенно для упрощенного HttpClient. Отсутствие "Content-Type" особенно важно, так как Angular автоматически создает Content-Type (есть склонность добавлять Content-Type = undefined. Не, так как это создаст проблемы при различных обстоятельствах и, возможно, не хорошая практика тоже). Как только нет Content-Type, браузер автоматически добавит 'multipart/form-data' и связанные параметры. Обратите внимание, что здесь используется Spring Boot, хотя это не должно иметь значения.
Вот какой-то псевдокод - прошу прощения за phat пальцы. Надеюсь, это поможет:
MyFileUploadComponent (.html):
...
<input type="file" (change)=fileEvent($event)...>
MyFileUploadComponent (.ts) вызывает MyFileUploadService (.ts) для fileEvent:
...
public fileEvent($event) {
const fileSelected: File = $event.target.files[0];
this.myFileUploadService.uploadFile(fileSelected)
.subscribe( (response) => {
console.log('set any success actions...');
return response;
},
(error) => {
console.log('set any error actions...');
});
}
MyFileUploadService.ts:
...
public uploadFile(fileToUpload: File) {
const _formData = new FormData();
_formData.append('file', fileToUpload, fileToUpload.name);
return<any>post(UrlFileUpload, _formData);
//note: no HttpHeaders passed as 3d param to POST!
//So no Content-Type constructed manually.
//Angular 4.x-6.x does it automatically.
}
Ответ 2
Для загрузки файла мы можем опубликовать данные в виде multipart/form-data. Для этого мы должны использовать класс FormData. Вот пример.
Шаблон:
<form #yourForm="ngForm" (ngSubmit)="onSubmit()">
<input type="text" [(ngModel)]="Name" name="Name"/>
<input type="file" #fileupload [(ngModel)]="myFile" name="myFile" (change)="fileChange(fileupload.files)"/>
<button type="submit">Submit</button>
</form>
Компонент:
import { Http, Response, Headers, RequestOptions } from '@angular/http';
/* When we select file */
Name:string;
myFile:File; /* property of File type */
fileChange(files: any){
console.log(files);
this.myFile = files[0].nativeElement;
}
/* Now send your form using FormData */
onSubmit(): void {
let _formData = new FormData();
_formData.append("Name", this.Name);
_formData.append("MyFile", this.myFile);
let body = this._formData;
let headers = new Headers();
let options = new Options({
headers: headers
});
this._http.post("http://example/api/YourAction", body, options)
.map((response:Response) => <string>response.json())
.subscribe((data) => this.message = data);
}
API для загрузки файла:
https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/sending-html-form-data-part-2
Ответ 3
это очень просто
component.html будет выглядеть как
<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>
пока в файле ts он будет выглядеть как
public fileUploader(event) {
const elem = event.target;
if (elem.files.length > 0) {
console.log(elem.files[0]);
}
// ...
}
Ответ 4
чтобы скачать файл с угловым попробуйте с этим, он работает "
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();
});
}
"
Ответ 5
<form [formGroup]="uploadForm" (ngSubmit)="onSubmit()">
Select image to upload:
<input type="file" name="avatar" id="fileToUpload" formControlName="file1" (change)="fileEvent($event)">
<input type="submit" value="Upload Image" name="submit">
</form>
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-praveen',
templateUrl: './praveen.component.html',
styleUrls: ['./praveen.component.css']
})
export class PraveenComponent implements OnInit {
constructor(private httpClient:HttpClient) { }
uploadForm = new FormGroup ({
file1: new FormControl()
});
filedata:any;
fileEvent(e){
this.filedata=e.target.files[0];
console.log(e);
}
onSubmit() {
let formdata = new FormData();
console.log(this.uploadForm)
formdata.append("avatar",this.filedata);
this.httpClient
.post<any>("http://localhost:3040/uploading",formdata)
.subscribe((res)=>{console.log(res});
}
ngOnInit() {
}
}
Ответ 6
Пожалуйста, используйте код ниже для загрузки файла.
HTML-код:
<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 из html с именем файла и путем к файлу в качестве параметров.
код компонента:
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;
}
Пожалуйста, дайте мне знать, если вы все еще сталкиваетесь с какой-либо проблемой.