简体   繁体   English

角度2中的图片上传问题:

[英]Image Upload issue in angular 2:

Image Upload issue in angular 2: 角度2中的图片上传问题:

We have a problem with uploading images into mysql as 'blob data' using angular 2.We dont know How to parse image into blob data 我们使用angular 2将图像作为“ blob数据”上传到mysql中时遇到问题。我们不知道如何将图像解析为blob数据

image.html: image.html:

<input type="file"  class="fileinput btn-primary" name="file" id="file" formControlName="file"
                        title="Browse image" [(ngModel)]="student.file" (change)="onChange($event)" />

image.component.ts: image.component.ts:

            file: File;
            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);

In Json 在杰森

   Student(
    name: string,
    class:string,
    file: any,
    rollNo: number): Observable<any> {
    let requestData = {
        name: name,
        class: class,
        photo: {
            data: file,
            contentType: "multipart/form-data"
        },
        rollNo: rollNo,
    };
    return this.http.post(this.studentUrl, requestData)
        .map(response => {
            return response;
        });
}

When we run this code it shows following error. 当我们运行此代码时,它显示以下错误。

Exception 例外

"Caused by: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing

If any plugin or directives for this? 是否为此使用任何插件或指令?

I used below code to solve similar problem 我用下面的代码来解决类似的问题

This is my file element in COMPONENTNAME.component.html 这是我在COMPONENTNAME.component.html中的文件元素

<input type="file" (change)="fileChange($event)">

Create fileChange function to your COMPONENT.component.ts 为您的COMPONENT.component.ts创建fileChange函数

private fileChange(event: any) {
    let reader = new FileReader();
    let imageBlob: any;
    reader.onload = (fileReadEvent: any) => {
        imageBlob = fileReadEvent.target.result;
    };
    reader.readAsDataURL(event.target.files[0]);
}

when you upload image it will call fileChange method and readAsDataURL method will be triggered and imageBlob variable will be having image as blob. 当您上传图片时,它将调用fileChange方法,并且将触发readAsDataURL方法,并且imageBlob变量会将图片作为blob。

Hope this will solve your problem!! 希望这能解决您的问题!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM