首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用cropper和ng文件上传

使用cropper和ng文件上传
EN

Stack Overflow用户
提问于 2015-09-18 22:59:59
回答 1查看 1K关注 0票数 6

我正在使用ng文件上传预览和上传图像。在上传图片之前,我希望让用户对图像进行裁剪。我尝试使用ng-img-裁剪,但这没有我想要的特性(纵横比定制),但裁剪(https://github.com/fengyuanchen/cropper/)。我现在唯一的问题是如何使用裁剪器对图像进行预览。图像src最终成为一个blob ie "blob:XYZ“。有人用这种方法成功地使用过农作物吗?有可能吗?

EN

回答 1

Stack Overflow用户

发布于 2020-02-16 23:48:38

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

组件

代码语言:javascript
复制
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 = '';
  }

}

组件模板

代码语言:javascript
复制
<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>

节点控制器

代码语言:javascript
复制
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
        });
    }
});
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32662262

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档