首页 > 解决方案 > 角度上传图片到服务器

问题描述

我是新来的。实际上,我需要知道如何将图像上传到服务器。因为当我尝试上传时,我得到了这个错误。

图像-1

图像-2

这是我的代码

HTML

<input type="file" name="files" (change)="fileUpload($event)" accept='image/gif' />

零件

fileUpload(event:any){
  this.image = event.target.files[0].name;
    let itemCode = this.activatedRoute.snapshot.paramMap.get('id');
   
    return this.http.post(environment.apiBaseUrl + environment.path + '/data/uploadgif',  {file: this.image, menuCode: itemCode})
    .subscribe((data) => {
      if(data['status']['code'] === 0) {
        document.location.href = environment.url;
      } else {

      }
    });
}

希望大家能帮助我提前谢谢

标签: angulartypescriptfile-upload

解决方案


这是上传图像的简单方法。

function handleInputChange(e) {
    var file = e.dataTransfer ? e.dataTransfer.files[0] : e.target.files[0];
    var pattern = /image-*/;
    var reader = new FileReader();
    if (!file.type.match(pattern)) {
      alert('invalid format');
      return;
    }
    reader.onload = this._handleReaderLoaded.bind(this);
    reader.readAsDataURL(file);
}

function _handleReaderLoaded(e) {
    let reader = e.target;

    const result = reader.result;
    // this.openSnackBar(result.length,"OK")
    if (!result) {
      this.openSnackBar("Cannot read", "OK")
      this.imageSrc = '';
    }
    if (result.length > 400000) {
      this.openSnackBar("File size should be less than 300KB", "OK")
      this.imageSrc = '';
    }
    else {
      this.imageSrc = reader.result;
    }
  }
<input type="file" id="fileupload" (change)="handleInputChange($event)">
  <label for="fileupload" class="custom-file-upload">
    <mat-icon style="font-size: large; vertical-align: middle;">attach_file</mat-icon>
  Select</label>

所以你必须基本上将图像转换为base64,然后上传到服务器。multer如果您nodejs用作服务器,则可以使用。


推荐阅读