简体   繁体   中英

Image Upload issue in angular 2:

Image Upload issue in angular 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

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:

            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

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

Create fileChange function to your COMPONENT.component.ts

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.

Hope this will solve your problem!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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