angular - 使用带有 ng-file-upload 的cropper

标签 angular file-upload crop ng-file-upload cropperjs

我正在使用 ng-file-upload 来预览和上传图像。在上传图像之前,我想让用户裁剪图像。我尝试使用 ng-img-crop,但它没有我想要的功能(纵横比自定义),但是cropper 有( https://github.com/fengyuanchen/cropper/ )。我现在唯一的问题是如何使用cropper 裁剪图像的预览。图像 src 最终成为一个 blob,即“blob:XYZ”。有没有人以这种方式成功使用过cropper?是否可以?

最佳答案

  • 保存您从 this.cropper.getCroppedCanvas().toBlob() 获得的 blob通过将其附加到状态。
  • 将保存的 blob 传递给 File save() 中的构造函数函数通过将其推送到第一个参数 fileBits
  • multer 的帮助下处理后端上传

  • 成分
    import { AfterViewInit, Component, ElementRef, Input, OnDestroy, OnInit, ViewChild } from '@angular/core';
    import { default as Cropper } from 'cropperjs';
    import { FileItem, FileUploader } from 'ng2-file-upload';
    import { UserService } from '../services/user.service';
    import { User } from '../models/core';
    
    @Component({
      selector: 'app-image-cropper',
      templateUrl: './image-cropper.component.html',
      styleUrls: ['./image-cropper.component.scss']
    })
    export class ImageCropperComponent implements OnInit, AfterViewInit, OnDestroy {
    
    
      @ViewChild('imageElement', {static: false})
      public imageElement: ElementRef;
    
      @Input()
      public imageSource: string;
    
      public imageBlob: Blob;
      public uploader: FileUploader;
      private cropper: Cropper;
    
      public constructor(private userService: UserService) {}
    
      public ngAfterViewInit() {
        this.cropper = new Cropper(this.imageElement.nativeElement, {
          zoomable: false,
          scalable: false,
          responsive: true,
          autoCropArea: 1,
          aspectRatio: 1,
          viewMode: 1,
          crop: (event) => {
            this.cropper.getCroppedCanvas().toBlob((blob) => {
              this.imageBlob = blob;
              console.log('Crop saved as a Blob');
            });
          }
        });
      }
    
      public save() {
        const date: number = new Date().getTime();
        // Put the blob into the fileBits array of the File constructor
        const file = new File([this.imageBlob], 'photo', {type: 'image/png', lastModified: date});
        const fileItem = new FileItem(this.uploader, file, {});
        this.uploader.queue.push(fileItem);
        fileItem.upload();
      }
    
      ngOnInit() {
        this.userService.user$.subscribe((user: User) => {
          this.uploader = new FileUploader({url: '/api/profile/' + user.username + '/avatar', itemAlias: 'photo'});
          this.uploader.onAfterAddingFile = (file) => {
            file.withCredentials = false;
          };
          this.uploader.onCompleteItem = (item: any, response: any, status: any, headers: any) => {
            console.log(response);
          };
        });
      }
    
      ngOnDestroy(): void {
        this.imageBlob = undefined;
        this.imageSource = '';
      }
    
    }
    
    
    组件模板
    <div class="modal-content">
      <div class="modal-header">
        <p class="modal-title font-weight-bold" id="crop-modal-title"><i></i>Crop</p>
        <button type="button" class="close" data-dismiss="modal"
                (click)="activeModal.close('Close click')">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
    
        <div class="img-container">
          <img #imageElement [src]="imageSource" crossorigin>
        </div>
        <button type="button" class="button button-primary"
                (click)="save()">
        </button>
      </div>
    </div>
    
    
    节点 Controller
    import { Request, Response, Router } from 'express';
    import * as util from 'util';
    import * as fs from 'fs';
    import * as multer from 'multer';
    
    Router.post('/profile/:username/avatar/', upload.single('photo'), async (req: Request, resp: Response) => {
        try {
            console.log(req.file);
            // Do something with the uploaded file here
            const fsUnlinkPromisified = (util as any).promisify(fs.unlink);
            await fsUnlinkPromisified(req.file.path);
        } catch (error) {
            console.log(error);
            return resp.send({
                msg: 'Upload failed',
                status: 400
            });
        }
    });
    

    关于angular - 使用带有 ng-file-upload 的cropper,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32662262/

    相关文章:

    angular - 如何在 ng2-smart-table 中添加自定义 css

    Angular 4 : Disable button in ngFor after click

    typescript - 在 Angular2 中加载数据时的加载器

    css - 部署时未加载字体

    javascript - 我怎样才能获得与 Medium.com 的功能标题相似的图像? (裁剪图像)

    swift - 检测具有白色背景的 UIImage 的边界边缘并在 Swift 中裁剪它

    c# - 如何使用 Microsoft Graph API 休息调用在 C# 中上传超过 4MB

    java - 如何修复 org.jvnet.mimepull.MIMEParsingException?

    javascript - 如何使用 AngularJS 表单上传图像 - 后端 : PHP

    unity-game-engine - 团结| 5.x 版本中的 'gameobject.renderer.material.color'