首页 > 解决方案 > 使用asp.net web api在Angular6中上传多个图像

问题描述

我正在尝试使用asp.net web api在Angular中上传多个图像。我不知道我错在哪里,但我无法上传我的图像。请帮助我。以下是我的代码

上传-images.component.html

<div class="container" style="margin-top:100px">
<form #imageForm="ngForm">
<div>
  <img *ngFor="let url of urls" [src]="url" style="width:250px;height:200px">
   <input  type="file" #Image multiple (change)="handleFileInput($event)" accept="image/">
   <button type="submit" (click)="upload()" class="btn btn-large btn-submit">Upload Image</button>
</div>

上传图片.component.ts

import { Component, OnInit } from '@angular/core';
import { UploadImagesService } from '../_shared/upload-images.service';

@Component({
  selector: 'app-upload-images',
  templateUrl: './upload-images.component.html',
  styles: []
})
export class UploadImagesComponent implements OnInit {
  imageUrl:string="./assets/images/customer-img1.jpg";
  urls = new Array<string>();
  fileToUpload:Array<File> =[]
  selctedFileName:string[] = []

  constructor(private uploadService:UploadImagesService) { }

 ngOnInit() {
 }

handleFileInput(fileInput:any){
 this.urls=[]
 this.fileToUpload = <Array<File>>fileInput.target.files

for(let i=0;i<this.fileToUpload.length;i++){

  //getting photos name
 console.log( this.fileToUpload[i].name)     
 //preview of the images
 var reader = new FileReader();
 reader.onload = (event:any)=>{
   this.urls.push(event.target.result)
 }
 reader.readAsDataURL(this.fileToUpload[i]);

 this.selctedFileName.push(this.fileToUpload[i].name)
 }
}
upload(){

  this.uploadService.postFile(this.fileToUpload)
  .subscribe(data=>{
    console.log(this.fileToUpload);

  })
 }
}

上传图片.service.ts

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

@Injectable({
 providedIn: 'root'
})
export class UploadImagesService {

 constructor(private http:HttpClient) { }

 fileToUpload:Array<File> = []

 postFile(fileToUpload:Array<File>){
  const endpoint="http://localhost:49235/api/UploadImage";
  const formData:FormData = new FormData();

  for(var i= 0;i<this.fileToUpload.length;i++)
  {
    formData.append('Image',fileToUpload[i],fileToUpload[i].name);
  }

  return this.http.post(endpoint,formData);
  }
 }

下面是我的 C# 代码

using BackEnd.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;

namespace BackEnd.Controllers
{
public class ImagesController : ApiController
{
    [HttpPost]
    [AllowAnonymous]
    [Route("api/UploadImage")]
    public HttpResponseMessage UploadImage()
    {
        string imageName = null;
        int i = 0;
        var httpRequest = HttpContext.Current.Request;   
        if (httpRequest.Files.Count > 0)
        {
         foreach(string file in httpRequest.Files)
           {
           var postedFile = httpRequest.Files[i];
                imageName = new  
             String(Path.GetFileNameWithoutExtension(postedFile.FileName)
                .Take(10).ToArray()).Replace(" ", "-");
                imageName = imageName + 
                     DateTime.Now.ToString("yymmssfff") + 
                    Path.GetExtension(postedFile.FileName);

 var filePath = HttpContext.Current.Server.MapPath("~/images/" + 
  postedFile.FileName);
                postedFile.SaveAs(filePath);





     using (ApplicationDbContext _context = new ApplicationDbContext())
                {
                    image Image = new image()
                    {
                        ImageName = imageName
                    };
                    _context.Images.Add(Image);
                    _context.SaveChanges();
                }

                i++;
           }
        }


        return Request.CreateResponse(HttpStatusCode.Created);
    }
   } 
}

当我选择图像时,我可以预览图像。

从这个链接开始的教程

仍然没有找到任何解决方案......请帮助我不知道我的代码哪里错了。谢谢。

标签: c#asp.netapiwebangular6

解决方案


推荐阅读