Codeando en Angular 9
file.service.ts
import {
Injectable
} from '@angular/core';
import {
HttpClient,
HttpHeaders,
HttpErrorResponse
} from '@angular/common/http';
import {
throwError
} from 'rxjs';
import {
catchError,
} from 'rxjs/operators';
import {
environment
} from '../../environments/environment';
const httpOptions = {
headers: new HttpHeaders({
enctype: 'multipart/form-data'
})
};
@Injectable({
providedIn: 'root'
})
export class FileService {
constructor(
private http: HttpClient,
) {}
uploadFile(fileUpload: File, id: number) {
const formData: FormData = new FormData();
formData.append('File', fileUpload, fileUpload.name);
return this.http
.post(environment.baseUrl + `uploadfile/${id}`, formData, httpOptions)
.pipe(
catchError(this.handleError)
);
}
private extractData(res: Response) {
const body = res;
return body || {};
}
private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
console.error('An error occurred:', error.error.message);
} else {
console.error(
`Backend returned code ${error.status}, ` +
`body was: ${error.message}`);
}
return throwError('Something bad happened; please try again later.');
}
}
file.component.ts
import {
Component,
OnInit,
} from '@angular/core';
import {
FileService
} from '../../services/file.service';
import {
FormBuilder,
FormGroup,
Validators
} from '@angular/forms';
@Component({
selector: 'file',
templateUrl: './file.component.html',
styleUrls: ['./file.component.css']
})
export class FileComponent implements OnInit {
validateForm: FormGroup;
constructor(
private fileService: FileService,
private fb: FormBuilder,
) {}
ngOnInit(): void {
this.validateForm = this.fb.group({
img1: [null, [Validators.nullValidator]],
img1Source: [null, [Validators.nullValidator]],
});
}
onFileChange(event) {
if (event.target.files.length > 0) {
const file = event.target.files[0];
this.validateForm.patchValue({
img1Source: file
});
}
}
save(fileUp: File) {
this.fileService.uploadFile(fileUp, id)
.subscribe(
(res) => {
},
(error) => {
this.toastr.error('Error al insertar datos');
}
);
}
}
file.component.html
<div class="container">
<div class="row">
<form [formGroup]="validateForm" (ngSubmit)="save(validateForm.value)" novalidate>
<div class="form-group row">
<label for="img1" class="col-3 col-form-label">imágen 1</label>
<div class="col-9">
<input type="file" class="form-control-file" formControlName="img1" id="img1" (change)="onFileChange($event)">
</div>
</div>
<button type="submit" class="btn btn-outline-primary">
Crear <fa-icon [icon]="faPlus"></fa-icon>
</button>
</form>
</div>
</div>
Codeando en C#
FileController.cs
using System;
using System.IO;
using System.Web;
using System.Web.Http;
namespace api.Controllers
{
[RoutePrefix("api/uploadfile")]
public class FileController : ApiController
{
private routineEntities db = new routineEntities();
public IHttpActionResult uploadfile()
{
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count <= 0)
{
return Json(500);
}
var fileSave = httpRequest.Files[0];
var filePath = HttpContext.Current.Server.MapPath("~/UploadedFiles/" + fileSave);
try
{
postedFile.SaveAs(filePath);
}
catch (Exception ex)
{
throw ex;
}
return Json(fileSave);
}
}
}