DEV Community

Nguyễn Hữu Hiếu
Nguyễn Hữu Hiếu

Posted on • Edited on

@kolkov/angular-editor: upload image using custom service

Problem

I cannot upload images using version 1.2.0 of the library @kolkov/angular-editor.

So many issues related to that and seem to be this cannot be fixed soon. So I decided to use other version and below is our solution to fix that

Solution

Version

angular: v10.0
@kolkov/angular-editor: v1.1.5
Enter fullscreen mode Exit fullscreen mode

Frontend - angular

import { AngularEditorConfig } from '@kolkov/angular-editor';

editorConfig: AngularEditorConfig = {
  ...,
  uploadUrl: "http://localhost:8080/image/upload"
  ...
};

Enter fullscreen mode Exit fullscreen mode

Backend - java

class UploadFile {
  public String imageUrl;
}

@PostMapping(path = "/files/upload/image/by/angular-editor",
        consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
        produces = MediaType.APPLICATION_JSON_VALUE)
public UploadFile uploadImageByAngularEditor(
      @RequestPart("file") MultipartFile file
    ) {
    // using your own service to save file
    ...
    // this is the image URL
    String imageUrl = "your image url"; 
    UploadFile response = new UploadFile();
    response.setImageUrl(imageUrl);
    return response;
}
Enter fullscreen mode Exit fullscreen mode

Backend - your system

  • Create Post API that handle input and return output adapt:
  • Input: MultipartFile that have file field in request
  • Ouput: return json that have imageUrl field like this { imageUrl: "" }

Explain

  • When set uploadUrl in fontend => every time you click upload image it will send a post request to uploadUrl
  • That request have MultipartFile in request, it expected to receive {"image Url": ""} in response
  • The below code is similar to post request:
import { HttpClient, HttpEvent } from '@angular/common/http';
import { UploadResponse } from '@kolkov/angular-editor';

export class FileService {
  constructor(private httpClient: HttpClient) {}

  uploadImageByAngularEditor(file: File): 
Observable<HttpEvent<UploadResponse>> {
    const url = `http://localhost:8080/upload/image`;
    const formData: FormData = new FormData();
    formData.append('file', file);
    return this.httpClient.post<UploadResponse>(url, formData, {
      observe: 'events',
    }).pipe(tap(console.log));
  }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
ricardo_torres_6381dd6f06 profile image
Ricardo Torres

I am facing the same error, What other editor did you decide to select ?