Subir archivos con Angular y WebApi



app.component.html

<form [formGroup]="form" (ngSubmit)="onSubmit()" class="form-horizontal form-control-sm">
  <div class="form-row">
    <label for="nombre" class="col-sm-1 control-label form-control-sm text-right">Nombre</label>
    <div class="col-sm-1">
      <input class="form-control form-control-sm" formControlName="nombre">
    </div>
  </div>

  <div class="form-row mb-2">
    <label for="foto" class="col-sm-1 control-label form-control-sm text-right">Foto</label>
    <div class="col-sm-3">
      <img src="./assets/noimage.png" id="previewFoto" name="previewFoto" style="width: 150px; height: 150px;cursor: pointer" onClick="document.getElementById('foto').click();"
      />
    </div>
    <input class="form-control form-control-sm" id="foto" type="file" accept=".xlsx" (change)="upload($event)"
      #fileInput style="display: none">
  </div>

  <input type="submit" value="Guardar" [disabled]="!form.valid" class="btn btn-primary col-sm-1">
</form>


app.component.ts

import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from "@angular/forms";
import { DatosService } from './_servicios/datos.service';
import { Datos } from './_modelos/datos';
import { CustomResponse } from './_modelos/custom-response';
import { ResponseMessageCode } from './_servicios/enumerados';
//import { Archivo } from './_modelos/archivo';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  datos = new Datos();
  form: FormGroup;

  constructor(private fb: FormBuilder, private data : DatosService) {
    this.createForm();
  }

  createForm() {
    this.form = this.fb.group({     
  nombre: [''],
      foto: ['']
    });
  }

  upload(event) {
    this.onFileChange(event);
  }

  onFileChange(event) {
    if (event.target.files.length > 0) {
      let archivoSeleccionado = event.target.files[0];

      let reader = new FileReader();
      reader.readAsDataURL(archivoSeleccionado);
      let _this = this;

      reader.onloadend = function () {
        _this.form.patchValue({
          foto: (<string>reader.result).split('base64,')[1]
        });
      }
    }
  }

  onSubmit() {       
    this.datos.nombre = this.form.get('nombre').value;

    if (this.datos.contenido != 'undefined') {
      this.datos.contenido = this.form.get('foto').value;
    }

    this.data.guardar(this.datos).subscribe(
      (response: CustomResponse<any>) => {
        if (response.messageCode == ResponseMessageCode.OK) {
          console.log("todo ok");
        } else {
          console.log("mal");     
        }
      }
    );
  }

  ngOnInit() {
  }
}


app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { ReactiveFormsModule, FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
import { RouterModule, Routes } from '@angular/router';

const routes: Routes = [
  { path: 'home', component: AppComponent }
]

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpModule,
    HttpClientModule,
    FormsModule,
    ReactiveFormsModule,
    RouterModule.forRoot(routes)
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }



datos.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})

export class DatosService {
  constructor(public http: HttpClient) { }

  public guardar(datos): Observable<any> {
    return this.http.post<any>("http://localhost/servicios/api/creditos/subirarchivo", datos);
  }
}

custom-response.ts

export class CustomResponse<T> {
   messageCode: number;
   message: string;
   data: T;
}

datos.ts

export class Datos {
    nombre: string;
    contenido: string;
}


WebApi C#

[AllowAnonymous]
[OverrideAuthentication]
[HttpPost]
public IHttpActionResult SubirArchivo(Arch datos)
{
var path = System.Web.HttpContext.Current.Server.MapPath("~") + @"\xls\archivo.xlsx";
if (File.Exists(path))
File.Delete(path);

File.WriteAllBytes(path, datos.Contenido);

var mensaje = new { error = false, mensaje = "" };

return this.Ok(mensaje);
}

public class Arch
{
    [JsonProperty("nombre")]
    public string Nombre { get; set; }
    [JsonProperty("contenido")]
    public byte[] Contenido { get; set; }
}

No hay comentarios:

Publicar un comentario