角度文件上传


190

我是Angular的初学者,我想知道如何创建Angular 5 File upload部分,我尝试查找任何教程或文档,但是在任何地方都看不到任何东西。有什么想法吗?我正在尝试ng4-文件,但不适用于Angular 5


2
那么您要拖放还是简单的Choose Filebtn上传?在这两种情况下,您只需使用FormData
ddw

4
看一下primeng,我已经使用了一段时间了,它可以与angular v5一起使用。primefaces.org/primeng/#/fileupload
Bunyamin Coskuner

对于那些只需要将JSON上传到客户端的人,请查看以下问题:stackoverflow.com/questions/54971238/…–
AnthonyW

Answers:


423

这是一个将文件上传到api的工作示例:

步骤1:HTML模板(file-upload.component.html)

定义类型的简单输入标签file。向(change)-event 添加函数以处理选择文件。

<div class="form-group">
    <label for="file">Choose File</label>
    <input type="file"
           id="file"
           (change)="handleFileInput($event.target.files)">
</div>

步骤2:在TypeScript(file-upload.component.ts)中上传处理

为所选文件定义默认变量。

fileToUpload: File = null;

创建在(change)文件输入标签的-event中使用的函数:

handleFileInput(files: FileList) {
    this.fileToUpload = files.item(0);
}

如果要处理多文件选择,则可以遍历此文件数组。

现在,通过调用file-upload.service创建文件上传功能:

uploadFileToActivity() {
    this.fileUploadService.postFile(this.fileToUpload).subscribe(data => {
      // do something, if upload success
      }, error => {
        console.log(error);
      });
  }

步骤3:文件上传服务(file-upload.service.ts)

通过POST方法上传文件时,您应该使用FormData,因为这样您可以将文件添加到http请求中。

postFile(fileToUpload: File): Observable<boolean> {
    const endpoint = 'your-destination-url';
    const formData: FormData = new FormData();
    formData.append('fileKey', fileToUpload, fileToUpload.name);
    return this.httpClient
      .post(endpoint, formData, { headers: yourHeadersConfig })
      .map(() => { return true; })
      .catch((e) => this.handleError(e));
}

因此,这是一个非常简单的工作示例,我每天在工作中都会使用它。


6
@Katie您启用了polyfills吗?
Gregor Doroschenko '18

2
@GregorDoroschenko我正在尝试使用包含有关文件的其他信息的模型,而我必须这样做才能使其正常工作:const invFormData: FormData = new FormData(); invFormData.append('invoiceAttachment', invoiceAttachment, invoiceAttachment.name); invFormData.append('invoiceInfo', JSON.stringify(invoiceInfo)); 控制器具有两个对应的参数,但是我必须在控制器中解析JSON。我的Core 2控制器不会自动在参数中提取模型。我的原始设计是带有文件属性的模型,但我无法使它正常工作
Papa Stahl

1
@GregorDoroschenko我尝试了此代码createContrat(fileToUpload: File, newContrat: Contrat): Observable<boolean> { let headers = new Headers(); const endpoint = Api.getUrl(Api.URLS.createContrat)); const formData: FormData =new FormData(); formData.append('fileKey', fileToUpload, FileToUpload.name); let body newContrat.gup(this.auth.getCurrentUser().token); return this.http .post(endpoint, formData, body) .map(() => { return true; }) }
OnnaB

1
@GregorDoroschenko对我来说不起作用。我在ws中发布:Content-Disposition: form-data; name="fileKey"; filename="file.docx" Content-Type: application/octet-stream <file>
OnnaB

1
@OnnaB如果将FormData用于文件和其他属性,则应将文件和其他属性解析为FormData。您不能同时使用FormData和body。
Gregor Doroschenko '18

23

这样,我将上传文件实施到项目中的Web API。

我为谁分享关注。

const formData: FormData = new FormData();
formData.append('Image', image, image.name);
formData.append('ComponentId', componentId);
return this.http.post('/api/dashboard/UploadImage', formData);

一步步

ASP.NET Web API

[HttpPost]
[Route("api/dashboard/UploadImage")]
public HttpResponseMessage UploadImage() 
{
    string imageName = null;
    var httpRequest = HttpContext.Current.Request;
    //Upload Image
    var postedFile = httpRequest.Files["Image"];
    //Create custom filename
    if (postedFile != null)
    {
        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/" + imageName);
        postedFile.SaveAs(filePath);
    }
}

HTML表格

<form #imageForm=ngForm (ngSubmit)="OnSubmit(Image)">

    <img [src]="imageUrl" class="imgArea">
    <div class="image-upload">
        <label for="file-input">
            <img src="upload.jpg" />
        </label>

        <input id="file-input" #Image type="file" (change)="handleFileInput($event.target.files)" />
        <button type="submit" class="btn-large btn-submit" [disabled]="Image.value=='' || !imageForm.valid"><i
                class="material-icons">save</i></button>
    </div>
</form>

TS文件以使用API

OnSubmit(Image) {
    this.dashboardService.uploadImage(this.componentId, this.fileToUpload).subscribe(
      data => {
        console.log('done');
        Image.value = null;
        this.imageUrl = "/assets/img/logo.png";
      }
    );
  }

服务TS

uploadImage(componentId, image) {
        const formData: FormData = new FormData();
        formData.append('Image', image, image.name);
        formData.append('ComponentId', componentId);
        return this.http.post('/api/dashboard/UploadImage', formData);
    }

1
不发送标头的方式是什么?
Shalom Dahan

14

非常简单快捷的方法是使用ng2-file-upload

通过npm安装ng2-file-upload。 npm i ng2-file-upload --save

首先,在模块中导入模块。

import { FileUploadModule } from 'ng2-file-upload';

Add it to [imports] under @NgModule:
imports: [ ... FileUploadModule, ... ]

标记:

<input ng2FileSelect type="file" accept=".xml" [uploader]="uploader"/>

在您的ts中:

import { FileUploader } from 'ng2-file-upload';
...
uploader: FileUploader = new FileUploader({ url: "api/your_upload", removeAfterUpload: false, autoUpload: true });

这是最简单的用法。要了解所有功能,请参阅演示


4
图片上传后如何获得回应?会有什么反应,文档缺少这一部分。
穆罕默德·沙扎德

7

我使用的是Angular 5.2.11,我喜欢Gregor Doroschenko提供的解决方案,但是我注意到上载的文件为零字节,我必须做一些小改动才能使它对我有用。

postFile(fileToUpload: File): Observable<boolean> {
  const endpoint = 'your-destination-url';
  return this.httpClient
    .post(endpoint, fileToUpload, { headers: yourHeadersConfig })
    .map(() => { return true; })
    .catch((e) => this.handleError(e));
}

以下几行(formData)对我不起作用。

const formData: FormData = new FormData();
formData.append('fileKey', fileToUpload, fileToUpload.name);

https://github.com/amitrke/ngrke/blob/master/src/app/services/fileupload.service.ts


6

好的,因为该线程出现在google的第一个结果中,对于其他有相同问题的用户,您不必像trueboroda所指出的那样重新设计轮子,就可以使用ng2-file-upload库,该库简化了上传角度为6和7的文件,您需要做的是:

安装最新的Angular CLI

yarn add global @angular/cli

然后安装rx-compat以解决兼容性问题

npm install rxjs-compat --save

安装ng2-file-upload

npm install ng2-file-upload --save

在模块中导入FileSelectDirective指令。

import { FileSelectDirective } from 'ng2-file-upload';

Add it to [declarations] under @NgModule:
declarations: [ ... FileSelectDirective , ... ]

在你的组件中

import { FileUploader } from 'ng2-file-upload/ng2-file-upload';
...

export class AppComponent implements OnInit {

   public uploader: FileUploader = new FileUploader({url: URL, itemAlias: 'photo'});
}

模板

<input type="file" name="photo" ng2FileSelect [uploader]="uploader" />

为了更好地理解,您可以检查以下链接: 如何使用Angular 6/7上传文件


1
感谢您的链接。在台式机上上传效果很好,但是我一生都无法在iOS等移动设备上进行上传。我可以从相机胶卷中选择一个文件,但上传时总是失败。有任何想法吗?仅供参考,请在移动Safari中运行此程序,而不是在已安装的应用程序中运行。
ScottN

1
@ScottN,您好,欢迎您,也许问题出在您使用的浏览器上?您是否与另一个测试了吗?
Mohamed Makkaoui,

1
嗨@Mohamed Makkaoui,谢谢您的回复。我确实在iOS的Chrome浏览器中尝试过,但结果仍然相同。我很好奇这是否是发布到服务器时的标题问题?我正在使用用.Net而不是AWS FYI编写的自定义WebAPI。
ScottN

1
@ScottN,您好,除非您使用此链接调试代码,否则我们将无法知道它是否是标题问题developers.google.com/web/tools/chrome-devtools/…,然后看看您收到了什么错误消息。
Mohamed Makkaoui,

6

我个人是使用ngx-material-file-input作为前端,使用Firebase作为后端来进行此操作。更精确地说,是将Cloud Firestore与后端的Firebase C Loud Storage for Backbase结合使用。下面的示例将文件限制为不大于20 MB,并且仅接受某些文件扩展名。我还使用Cloud Firestore存储指向上传文件的链接,但是您可以跳过此操作。

contact.component.html

<mat-form-field>
  <!--
    Accept only files in the following format: .doc, .docx, .jpg, .jpeg, .pdf, .png, .xls, .xlsx. However, this is easy to bypass, Cloud Storage rules has been set up on the back-end side.
  -->
  <ngx-mat-file-input
    [accept]="[
      '.doc',
      '.docx',
      '.jpg',
      '.jpeg',
      '.pdf',
      '.png',
      '.xls',
      '.xlsx'
    ]"
    (change)="uploadFile($event)"
    formControlName="fileUploader"
    multiple
    aria-label="Here you can add additional files about your project, which can be helpeful for us."
    placeholder="Additional files"
    title="Additional files"
    type="file"
  >
  </ngx-mat-file-input>
  <mat-icon matSuffix>folder</mat-icon>
  <mat-hint
    >Accepted formats: DOC, DOCX, JPG, JPEG, PDF, PNG, XLS and XLSX,
    maximum files upload size: 20 MB.
  </mat-hint>
  <!--
    Non-null assertion operators are required to let know the compiler that this value is not empty and exists.
  -->
  <mat-error
    *ngIf="contactForm.get('fileUploader')!.hasError('maxContentSize')"
  >
    This size is too large,
    <strong
      >maximum acceptable upload size is
      {{
        contactForm.get('fileUploader')?.getError('maxContentSize')
          .maxSize | byteFormat
      }}</strong
    >
    (uploaded size:
    {{
      contactForm.get('fileUploader')?.getError('maxContentSize')
        .actualSize | byteFormat
    }}).
  </mat-error>
</mat-form-field>

contact.component.ts(大小验证器部分)

import { FileValidator } from 'ngx-material-file-input';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

/**
 * @constructor
 * @description Creates a new instance of this component.
 * @param  {formBuilder} - an abstraction class object to create a form group control for the contact form.
 */
constructor(
  private angularFirestore: AngularFirestore,
  private angularFireStorage: AngularFireStorage,
  private formBuilder: FormBuilder
) {}

public maxFileSize = 20971520;
public contactForm: FormGroup = this.formBuilder.group({
    fileUploader: [
      '',
      Validators.compose([
        FileValidator.maxContentSize(this.maxFileSize),
        Validators.maxLength(512),
        Validators.minLength(2)
      ])
    ]
})

contact.component.ts(文件上传器部分)

import { AngularFirestore } from '@angular/fire/firestore';
import {
  AngularFireStorage,
  AngularFireStorageReference,
  AngularFireUploadTask
} from '@angular/fire/storage';
import { catchError, finalize } from 'rxjs/operators';
import { throwError } from 'rxjs';

public downloadURL: string[] = [];
/**
* @description Upload additional files to Cloud Firestore and get URL to the files.
   * @param {event} - object of sent files.
   * @returns {void}
   */
  public uploadFile(event: any): void {
    // Iterate through all uploaded files.
    for (let i = 0; i < event.target.files.length; i++) {
      const randomId = Math.random()
        .toString(36)
        .substring(2); // Create random ID, so the same file names can be uploaded to Cloud Firestore.

      const file = event.target.files[i]; // Get each uploaded file.

      // Get file reference.
      const fileRef: AngularFireStorageReference = this.angularFireStorage.ref(
        randomId
      );

      // Create upload task.
      const task: AngularFireUploadTask = this.angularFireStorage.upload(
        randomId,
        file
      );

      // Upload file to Cloud Firestore.
      task
        .snapshotChanges()
        .pipe(
          finalize(() => {
            fileRef.getDownloadURL().subscribe((downloadURL: string) => {
              this.angularFirestore
                .collection(process.env.FIRESTORE_COLLECTION_FILES!) // Non-null assertion operator is required to let know the compiler that this value is not empty and exists.
                .add({ downloadURL: downloadURL });
              this.downloadURL.push(downloadURL);
            });
          }),
          catchError((error: any) => {
            return throwError(error);
          })
        )
        .subscribe();
    }
  }

储存规则

rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
        allow read; // Required in order to send this as attachment.
      // Allow write files Firebase Storage, only if:
      // 1) File is no more than 20MB
      // 2) Content type is in one of the following formats: .doc, .docx, .jpg, .jpeg, .pdf, .png, .xls, .xlsx.
      allow write: if request.resource.size <= 20 * 1024 * 1024
        && (request.resource.contentType.matches('application/msword')
        || request.resource.contentType.matches('application/vnd.openxmlformats-officedocument.wordprocessingml.document')
        || request.resource.contentType.matches('image/jpg')
        || request.resource.contentType.matches('image/jpeg')
        || request.resource.contentType.matches('application/pdf')
                || request.resource.contentType.matches('image/png')
        || request.resource.contentType.matches('application/vnd.ms-excel')
        || request.resource.contentType.matches('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'))
    }
  }
}

2
看起来不错,但是为什么需要toString()contactForm声明?
trungk18

1
@ trungk18再检查一次,您说的toString()没用,编辑了我的答案。对于那些会阅读此评论的人,我fileUploadercontact.component.ts的结尾处有])].toString()})。现在,它只是:])]})
丹尼尔·丹尼尔内基

5
  1. 的HTML

    <div class="form-group">
      <label for="file">Choose File</label><br /> <input type="file" id="file" (change)="uploadFiles($event.target.files)">
    </div>

    <button type="button" (click)="RequestUpload()">Ok</button>
  1. ts文件
public formData = new FormData();
ReqJson: any = {};

uploadFiles( file ) {
        console.log( 'file', file )
        for ( let i = 0; i < file.length; i++ ) {
            this.formData.append( "file", file[i], file[i]['name'] );
        }
    }

RequestUpload() {
        this.ReqJson["patientId"] = "12"
        this.ReqJson["requesterName"] = "test1"
        this.ReqJson["requestDate"] = "1/1/2019"
        this.ReqJson["location"] = "INDIA"
        this.formData.append( 'Info', JSON.stringify( this.ReqJson ) )
            this.http.post( '/Request', this.formData )
                .subscribe(( ) => {                 
                });     
    }
  1. 后端Spring(java文件)

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class Request {
    private static String UPLOADED_FOLDER = "c://temp//";

    @PostMapping("/Request")
    @ResponseBody
    public String uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("Info") String Info) {
        System.out.println("Json is" + Info);
        if (file.isEmpty()) {
            return "No file attached";
        }
        try {
            // Get the file and save it somewhere
            byte[] bytes = file.getBytes();
            Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
            Files.write(path, bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "Succuss";
    }
}

我们必须在C驱动器中创建一个文件夹“ temp”,然后此代码将在控制台中打印Json并将上载的文件保存在创建的文件夹中


我们如何检索该文件?您对此有一些指导吗?
Siddharth Choudhary

另外,我的spring服务器在8080上运行,而angular服务器在3000上运行。现在当我将server_url标记为localhost:8080 / api / uploadForm时,它说不允许cors!
Siddharth Choudhary

byte [] bytes = file.getBytes(); 它将提供字节流..您可以将其转换为文件,对于cors问题,您可以在Google中找到解决方案
Shafeeq Mohammed

5

首先,您需要在Angular项目中设置HttpClient。

打开src / app / app.module.ts文件,导入HttpClientModule并将其添加到模块的imports数组中,如下所示:

import { BrowserModule } from '@angular/platform-browser';  
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';  
import { AppComponent } from './app.component';  
import { HttpClientModule } from '@angular/common/http';

@NgModule({  
  declarations: [  
    AppComponent,  
  ],  
  imports: [  
    BrowserModule,  
    AppRoutingModule,  
    HttpClientModule  
  ],  
  providers: [],  
  bootstrap: [AppComponent]  
})  
export class AppModule { }

接下来,生成一个组件:

$ ng generate component home

接下来,生成一个上传服务:

$ ng generate service upload

接下来,按如下所示打开src / app / upload.service.ts文件:

import { HttpClient, HttpEvent, HttpErrorResponse, HttpEventType } from  '@angular/common/http';  
import { map } from  'rxjs/operators';

@Injectable({  
  providedIn: 'root'  
})  
export class UploadService { 
    SERVER_URL: string = "https://file.io/";  
    constructor(private httpClient: HttpClient) { }
    public upload(formData) {

      return this.httpClient.post<any>(this.SERVER_URL, formData, {  
         reportProgress: true,  
         observe: 'events'  
      });  
   }
}

接下来,打开src / app / home / home.component.ts文件,并开始添加以下导入:

import { Component, OnInit, ViewChild, ElementRef  } from '@angular/core';
import { HttpEventType, HttpErrorResponse } from '@angular/common/http';
import { of } from 'rxjs';  
import { catchError, map } from 'rxjs/operators';  
import { UploadService } from  '../upload.service';

接下来,定义fileUpload和files变量,并按如下所示注入UploadService:

@Component({  
  selector: 'app-home',  
  templateUrl: './home.component.html',  
  styleUrls: ['./home.component.css']  
})  
export class HomeComponent implements OnInit {
    @ViewChild("fileUpload", {static: false}) fileUpload: ElementRef;files  = [];  
    constructor(private uploadService: UploadService) { }

接下来,定义uploadFile()方法:

uploadFile(file) {  
    const formData = new FormData();  
    formData.append('file', file.data);  
    file.inProgress = true;  
    this.uploadService.upload(formData).pipe(  
      map(event => {  
        switch (event.type) {  
          case HttpEventType.UploadProgress:  
            file.progress = Math.round(event.loaded * 100 / event.total);  
            break;  
          case HttpEventType.Response:  
            return event;  
        }  
      }),  
      catchError((error: HttpErrorResponse) => {  
        file.inProgress = false;  
        return of(`${file.data.name} upload failed.`);  
      })).subscribe((event: any) => {  
        if (typeof (event) === 'object') {  
          console.log(event.body);  
        }  
      });  
  }

接下来,定义可以用于上传多个图像文件的uploadFiles()方法:

private uploadFiles() {  
    this.fileUpload.nativeElement.value = '';  
    this.files.forEach(file => {  
      this.uploadFile(file);  
    });  
}

接下来,定义onClick()方法:

onClick() {  
    const fileUpload = this.fileUpload.nativeElement;fileUpload.onchange = () => {  
    for (let index = 0; index < fileUpload.files.length; index++)  
    {  
     const file = fileUpload.files[index];  
     this.files.push({ data: file, inProgress: false, progress: 0});  
    }  
      this.uploadFiles();  
    };  
    fileUpload.click();  
}

接下来,我们需要创建图像上传用户界面的HTML模板。打开src / app / home / home.component.html文件并添加以下内容:

       <div style="text-align:center; margin-top: 100px; ">

        <button mat-button color="warn" (click)="onClick()">  
            Upload  
        </button>  
    <input type="file" #fileUpload id="fileUpload" name="fileUpload" multiple="multiple" accept="image/*" style="display:none;" /></div>

查看本教程和这篇文章


4

使用Angular和Node.js上载文件的完整示例(快速)

HTML代码

            <div class="form-group">
                <label for="file">Choose File</label><br/>
                <input type="file" id="file" (change)="uploadFile($event.target.files)" multiple>
            </div>

TS组件代码

uploadFile(files) {
    console.log('files', files)
        var formData = new FormData();

    for(let i =0; i < files.length; i++){
      formData.append("files", files[i], files[i]['name']);
        }

    this.httpService.httpPost('/fileUpload', formData)
      .subscribe((response) => {
        console.log('response', response)
      },
        (error) => {
      console.log('error in fileupload', error)
       })
  }

节点Js代码

fileUpload API控制器

function start(req, res) {
fileUploadService.fileUpload(req, res)
    .then(fileUploadServiceResponse => {
        res.status(200).send(fileUploadServiceResponse)
    })
    .catch(error => {
        res.status(400).send(error)
    })
}

module.exports.start = start

使用multer上载服务

const multer = require('multer') // import library
const moment = require('moment')
const q = require('q')
const _ = require('underscore')
const fs = require('fs')
const dir = './public'

/** Store file on local folder */
let storage = multer.diskStorage({
destination: function (req, file, cb) {
    cb(null, 'public')
},
filename: function (req, file, cb) {
    let date = moment(moment.now()).format('YYYYMMDDHHMMSS')
    cb(null, date + '_' + file.originalname.replace(/-/g, '_').replace(/ /g,     '_'))
}
})

/** Upload files  */
let upload = multer({ storage: storage }).array('files')

/** Exports fileUpload function */
module.exports = {
fileUpload: function (req, res) {
    let deferred = q.defer()

    /** Create dir if not exist */
    if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir)
        console.log(`\n\n ${dir} dose not exist, hence created \n\n`)
    }

    upload(req, res, function (err) {
        if (req && (_.isEmpty(req.files))) {
            deferred.resolve({ status: 200, message: 'File not attached', data: [] })
        } else {
            if (err) {
                deferred.reject({ status: 400, message: 'error', data: err })
            } else {
                deferred.resolve({
                    status: 200,
                    message: 'File attached',
                    filename: _.pluck(req.files,
                        'filename'),
                    data: req.files
                })
            }
        }
    })
    return deferred.promise
}
}

1
httpService来自哪里?
詹姆士

@James httpService是有角度的http模块,用于对服务器进行http调用。您可以使用任何所需的http服务。从'@ angular / common / http'导入{HttpClientModule};
Rohit Parte

2

试试这个

安装

npm install primeng --save

进口

import {FileUploadModule} from 'primeng/primeng';

HTML

<p-fileUpload name="myfile[]" url="./upload.php" multiple="multiple"
    accept="image/*" auto="auto"></p-fileUpload>

1
我厌倦了上面的例子。但是我找不到./upload.php。
Sandeep Kamath

2
您应提供您的URL,而不是upload.php @sandeep kamath
Vignesh

1
@Vignesh感谢您的答复。但我发现我不给url属性加载文件,应该是默认属性。
Sandeep Kamath

1
如果我们采用这种方法,您能否解释一下如何在php中接收文件。
谢赫·阿尔巴兹

2

Angular 7/8/9中

链接

在此处输入图片说明

使用引导表格

<form>
    <div class="form-group">
        <fieldset class="form-group">

            <label>Upload Logo</label>
            {{imageError}}
            <div class="custom-file fileInputProfileWrap">
                <input type="file" (change)="fileChangeEvent($event)" class="fileInputProfile">
                <div class="img-space">

                    <ng-container *ngIf="isImageSaved; else elseTemplate">
                        <img [src]="cardImageBase64" />
                    </ng-container>
                    <ng-template #elseTemplate>

                        <img src="./../../assets/placeholder.png" class="img-responsive">
                    </ng-template>

                </div>

            </div>
        </fieldset>
    </div>
    <a class="btn btn-danger" (click)="removeImage()" *ngIf="isImageSaved">Remove</a>
</form>

组件类中

fileChangeEvent(fileInput: any) {
    this.imageError = null;
    if (fileInput.target.files && fileInput.target.files[0]) {
        // Size Filter Bytes
        const max_size = 20971520;
        const allowed_types = ['image/png', 'image/jpeg'];
        const max_height = 15200;
        const max_width = 25600;

        if (fileInput.target.files[0].size > max_size) {
            this.imageError =
                'Maximum size allowed is ' + max_size / 1000 + 'Mb';

            return false;
        }

        if (!_.includes(allowed_types, fileInput.target.files[0].type)) {
            this.imageError = 'Only Images are allowed ( JPG | PNG )';
            return false;
        }
        const reader = new FileReader();
        reader.onload = (e: any) => {
            const image = new Image();
            image.src = e.target.result;
            image.onload = rs => {
                const img_height = rs.currentTarget['height'];
                const img_width = rs.currentTarget['width'];

                console.log(img_height, img_width);


                if (img_height > max_height && img_width > max_width) {
                    this.imageError =
                        'Maximum dimentions allowed ' +
                        max_height +
                        '*' +
                        max_width +
                        'px';
                    return false;
                } else {
                    const imgBase64Path = e.target.result;
                    this.cardImageBase64 = imgBase64Path;
                    this.isImageSaved = true;
                    // this.previewImagePath = imgBase64Path;
                }
            };
        };

        reader.readAsDataURL(fileInput.target.files[0]);
    }
}

removeImage() {
    this.cardImageBase64 = null;
    this.isImageSaved = false;
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.