بررسی روش آپلود فایلها از طریق یک برنامهی Angular به یک برنامهی ASP.NET Core
نویسنده: وحید نصیری
تاریخ: ۱۳۹۶/۰۴/۱۸ ۱۳:۲۰
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
>ng g m UploadFile -m app.module --routing
>ng g c UploadFile/UploadFileSimple
>ng g cl UploadFile/Ticket
export class Ticket {
constructor(public description: string = "") {}
}
import { Ticket } from "./../ticket";
export class UploadFileSimpleComponent implements OnInit {
model = new Ticket(); <div class="container">
<h3>Support Form</h3>
<form #form="ngForm" (submit)="submitForm(form)" novalidate>
<div class="form-group" [class.has-error]="description.invalid && description.touched">
<label class="control-label">Description</label>
<input #description="ngModel" required type="text" class="form-control"
name="description" [(ngModel)]="model.description">
<div *ngIf="description.invalid && description.touched">
<div class="alert alert-danger" *ngIf="description.errors.required">
description is required.
</div>
</div>
</div>
<div class="form-group">
<label class="control-label">Screenshot(s)</label>
<input #screenshotInput required type="file" multiple (change)="fileChange($event)"
class="form-control" name="screenshot">
</div>
<button class="btn btn-primary" [disabled]="form.invalid" type="submit">Ok</button>
</form>
</div> (change)="fileChange($event)"
fileChange(event) {
const filesList: FileList = event.target.files;
console.log("fileChange() -> filesList", filesList);
}
C:\Program Files (x86)\Microsoft VS Code\resources\app\extensions\node_modules\typescript\lib\lib.dom.d.ts
{
"lib": [
"es2016",
"dom"
]
}
} import { Component, OnInit, ViewChild, ElementRef } from "@angular/core";
export class UploadFileSimpleComponent implements OnInit {
@ViewChild("screenshotInput") screenshotInput: ElementRef;
submitForm(form: NgForm) {
const fileInput: HTMLInputElement = this.screenshotInput.nativeElement;
console.log("fileInput.files", fileInput.files);
} >ng g s UploadFile/UploadFileSimple -m upload-file.module
import { Http, RequestOptions, Response, Headers } from "@angular/http";
import { Injectable } from "@angular/core";
import { Observable } from "rxjs/Observable";
import "rxjs/add/operator/do";
import "rxjs/add/operator/catch";
import "rxjs/add/observable/throw";
import "rxjs/add/operator/map";
import "rxjs/add/observable/of";
import { Ticket } from "./ticket";
@Injectable()
export class UploadFileSimpleService {
private baseUrl = "api/SimpleUpload";
constructor(private http: Http) {}
private extractData(res: Response) {
const body = res.json();
return body || {};
}
private handleError(error: Response): Observable<any> {
console.error("observable error: ", error);
return Observable.throw(error.statusText);
}
postTicket(ticket: Ticket, filesList: FileList): Observable<any> {
if (!filesList || filesList.length === 0) {
return Observable.throw("Please select a file.");
}
const formData: FormData = new FormData();
for (const key in ticket) {
if (ticket.hasOwnProperty(key)) {
formData.append(key, ticket[key]);
}
}
for (let i = 0; i < filesList.length; i++) {
formData.append(filesList[i].name, filesList[i]);
}
const headers = new Headers();
headers.append("Accept", "application/json");
const options = new RequestOptions({ headers: headers });
return this.http
.post(`${this.baseUrl}/SaveTicket`, formData, options)
.map(this.extractData)
.catch(this.handleError);
}
} postTicket(ticket: Ticket, filesList: FileList): Observable<any> {
const formData: FormData = new FormData();
for (const key in ticket) {
if (ticket.hasOwnProperty(key)) {
formData.append(key, ticket[key]);
}
} for (let i = 0; i < filesList.length; i++) {
formData.append(filesList[i].name, filesList[i]);
} const headers = new Headers();
headers.append("Accept", "application/json");
const options = new RequestOptions({ headers: headers });
return this.http
.post(`${this.baseUrl}/SaveTicket`, formData, options)
.map(this.extractData)
.catch(this.handleError); import { UploadFileSimpleService } from "./../upload-file-simple.service";
export class UploadFileSimpleComponent implements OnInit {
constructor(private uploadService: UploadFileSimpleService ) {} submitForm(form: NgForm) {
const fileInput: HTMLInputElement = this.screenshotInput.nativeElement;
console.log("fileInput.files", fileInput.files);
this.uploadService
.postTicket(this.model, fileInput.files)
.subscribe(data => {
console.log("success: ", data);
});
} namespace AngularTemplateDrivenFormsLab.Models
{
public class Ticket
{
public int Id { set; get; }
public string Description { set; get; }
}
} using System.IO;
using System.Threading.Tasks;
using AngularTemplateDrivenFormsLab.Models;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
namespace AngularTemplateDrivenFormsLab.Controllers
{
[Route("api/[controller]")]
public class SimpleUploadController : Controller
{
private readonly IHostingEnvironment _environment;
public SimpleUploadController(IHostingEnvironment environment)
{
_environment = environment;
}
[HttpPost("[action]")]
public async Task<IActionResult> SaveTicket(Ticket ticket)
{
//TODO: save the ticket ... get id
ticket.Id = 1001;
var uploadsRootFolder = Path.Combine(_environment.WebRootPath, "uploads");
if (!Directory.Exists(uploadsRootFolder))
{
Directory.CreateDirectory(uploadsRootFolder);
}
var files = Request.Form.Files;
foreach (var file in files)
{
//TODO: do security checks ...!
if (file == null || file.Length == 0)
{
continue;
}
var filePath = Path.Combine(uploadsRootFolder, file.FileName);
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
await file.CopyToAsync(fileStream).ConfigureAwait(false);
}
}
return Created("", ticket);
}
}
} SaveTicket(Ticket ticket)
formData.append(filesList[i].name, filesList[i]);
var files = Request.Form.Files; foreach (var file in files)
import { HttpEventType, HttpClient, HttpRequest } from '@angular/common/http';
http.request(new HttpRequest(
'POST',
URL,
body,
{
reportProgress: true
})).subscribe(event => {
if (event.type === HttpEventType.DownloadProgress) {
}
if (event.type === HttpEventType.UploadProgress) {
}
if (event.type === HttpEventType.Response) {
console.log(event.body);
}
}) postTicket(ticket: Ticket, filesList: FileList): Observable<HttpEvent<any>> {
//… the same as before
const headers = new HttpHeaders().set("Accept", "application/json");
return this.http
.post(`${this.baseUrl}/SaveTicket`, formData, {
headers: headers,
reportProgress: true,
observe: "events"
})
.map(response => response || {})
.catch((error: HttpErrorResponse) => {
console.error("observable error: ", error);
return Observable.throw(error.statusText);
});
} postTicket(ticket: Ticket, filesList: FileList): Observable<HttpEvent<any>> { {
headers: headers,
reportProgress: true,
observe: "events"
} queueProgress: number;
isUploading: boolean;
uploadTimeRemaining: number;
uploadTimeElapsed: number;
uploadSpeed: number;
submitForm(form: NgForm) {
const fileInput: HTMLInputElement = this.screenshotInput.nativeElement;
this.queueProgress = 0;
this.isUploading = true;
let startTime = Date.now();
this.uploadService.postTicket(this.model, fileInput.files).subscribe(
(event: HttpEvent<any>) => {
switch (event.type) {
case HttpEventType.Sent:
startTime = Date.now();
console.log("Request sent!");
break;
case HttpEventType.DownloadProgress:
case HttpEventType.UploadProgress:
if (event.total) {
this.queueProgress = Math.round(event.loaded / event.total * 100);
const timeElapsed = Date.now() - startTime;
const uploadSpeed = event.loaded / (timeElapsed / 1000);
this.uploadTimeRemaining = Math.ceil(
(event.total - event.loaded) / uploadSpeed
);
this.uploadTimeElapsed = Math.ceil(timeElapsed / 1000);
this.uploadSpeed = uploadSpeed / 1024 / 1024;
}
break;
case HttpEventType.Response:
this.queueProgress = 100;
this.isUploading = false;
console.log("Done! ResponseBody:", event.body);
break;
}
},
(error: HttpErrorResponse) => {
this.isUploading = false;
console.log(error);
}
);
} <div *ngIf="queueProgress > 0">
<table class="table">
<thead>
<tr>
<th width="15%">Event</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Elapsed time</strong></td>
<td nowrap>{{uploadTimeElapsed | number:'.1'}} second(s)</td>
</tr>
<tr>
<td><strong>Remaining time</strong></td>
<td nowrap>{{uploadTimeRemaining | number:'.1'}} second(s)</td>
</tr>
<tr>
<td><strong>Upload speed</strong></td>
<td nowrap>{{uploadSpeed | number:'.3'}} MB/s</td>
</tr>
<tr>
<td><strong>Queue progress</strong></td>
<td>
<div class="progress-bar progress-bar-info progress-bar-striped" role="progressbar"
aria-valuemin="0" aria-valuemax="100" [attr.aria-valuenow]="queueProgress"
[ngStyle]="{ 'width': queueProgress + '%' }">
{{queueProgress}}%
</div>
</td>
</tr>
</tbody>
</table>
</div>
<button class="btn btn-primary" [disabled]="form.invalid || isUploading" type="submit">Submit</button>
با تشکر از شما
public async Task<IActionResult> UploadFile(string id, [FromForm] IFormFile file)
public async Task<IActionResult> FileUpload(IFormFile file)
{
if (file == null || file.Length == 0)
{
return BadRequest();
}
using (var memoryStream = new MemoryStream())
{
await file.CopyToAsync(memoryStream);
var fileBytes = memoryStream.ToArray();
// ... save it
}
} public async Task<ServiceResult<FileContentResult>> GetByFileFolderId(int id)
{
var file = await FileRepository.GetByFileFolderId( id);
var locatedFile = (byte[])Convert.ChangeType(file.FileData64, typeof(byte[]));
var result= new FileContentResult(locatedFile, new
MediaTypeHeaderValue("application/pdf"))
{
FileDownloadName = "SomeFileDownloadName.pdf"
};
return Ok(result);
} getPDF(fileId): Observable<Blob> {
const uri = 'MyApiUri/GetByFileFolderId?id=' + fileId;
return this.http.get(uri, { responseType: 'blob' });
}
downloadFile(){
this.getPDF()
.subscribe(x => {
var newBlob = new Blob([x], { type: "application/pdf" });
const data = window.URL.createObjectURL(newBlob);
var link = document.createElement('a');
link.href = data;
link.download = "SomeFileDownloadName.pdf";
link.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }));
setTimeout(function () {
window.URL.revokeObjectURL(data);
link.remove();
}, 100);
});
}