Angular 2 图片上传前调整大小

Angular 2 Image resize before upload

我希望在将图像上传到服务器之前调整图像大小,目前我正在使用 ng2-imageupload,如下所示:

  <input id="media" class="inputfile" type="file" name="media" image-upload
  (imageSelected)="selected($event)"
  [resizeOptions]="resizeOptions" (change)="onChange($event)">

导出class WpMediaFormComponent { 文件:文件;

resizeOptions: ResizeOptions = {
    resizeMaxHeight: 768,
    resizeMaxWidth: 438
};

selected(imageResult: ImageResult) {
    console.log(imageResult);
   this.dataBlob = this.dataURItoBlob(imageResult.resized.dataURL); 
    let blob = this.dataURItoBlob(imageResult.resized.dataURL);
}

这就是returns一个对象,像这样:

dataURL:"data:image/jpeg;base64, DATA URI HERE"
type:"image/jpeg;"

然后我可以使用此函数将此对象转换为 blob:

dataURItoBlob(dataURI) {
        // convert base64/URLEncoded data component to raw binary data held in a string
        var byteString;
        if (dataURI.split(',')[0].indexOf('base64') >= 0)
            byteString = atob(dataURI.split(',')[1]);
        else
            byteString = decodeURI(dataURI.split(',')[1]);

        // separate out the mime component
        var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

        // write the bytes of the string to a typed array
        var ia = new Uint8Array(byteString.length);
        for (var i = 0; i < byteString.length; i++) {
            ia[i] = byteString.charCodeAt(i);
        }

        return new Blob([ia], {type:mimeString});
    }

在执行此操作之前,我使用以下代码将图像上传到服务器:

 onChange(event: EventTarget) {
        let eventObj: MSInputMethodContext = <MSInputMethodContext> event;
        let target: HTMLInputElement = <HTMLInputElement> eventObj.target;
        let files: FileList = target.files;
        this.file = files[0];
        console.log(this.file);
        //this.update.emit(this.file);
    }

有谁知道如何将 dataURItoBlob 方法返回的 blob 提供给文件上传 onChange 事件?

我有点迷路了。

您需要将数据 URI 转换为 Blob,然后将其发送回您的服务器。这可能会有所帮助:Convert Data URI to File then append to FormData

获得 blob 后,使用 FormData 和 Angular HTTP class 将其上传到服务器进行进一步处理应该很容易。

let formData = new FormData();
formData.append(blob);
this.http.post('your/api/url', fd).subscribe((response) => console.log(reponse);

所以我在@Brother Woodrow 的帮助下解决了这个问题,这个线程: How to convert Blob to File in JavaScript

这是我更新后的代码,我唯一需要更改的不仅仅是所选方法:

selected(imageResult: ImageResult) {
    // create a blob 
    let blob: Blob = this.dataURItoBlob(imageResult.resized.dataURL);
    // get the filename
    let fileName: string = imageResult.file.name;
    // create a file
    this.file = new File([blob], fileName);
    console.log(this.file);
    // event emitter send to container then to http post 
    this.update.emit(this.file);        
}

我现在可以上传 3MB,它们会在几秒钟内被推送到大约 150kB 的服务器,这对用户来说非常好,尤其是因为这个应用程序主要由移动设备使用。