Search code examples
phpangularhttp-post

GETTING ERROR POSTING FILE TO MYSQL - PHP-CRUD-API


I'm trying to upload an image using mevdschee's PHP-CRUD-API. I've tried almost everything.. theese are the service functions I've tried, using both FormData or simple json.

service.ts

addMapIcon(mapIcon:mapIcon): Observable<string>{
    let fd = new FormData;
    fd.append('active', mapIcon.active?'1':'0');
    fd.append('file',mapIcon.file);
    fd.append('name',mapIcon.name);
    return this.http.post<string>(this.iconApiUrl, fd);

..or even:

    return this.http.post<string>(this.iconApiUrl, fd, {
        headers: new HttpHeaders({
          'Content-Type': 'application/json',
          'Content-type':'multipart/form-data'
          + combination of others parameters
          }));
    
  }
addMapIcon(mapIcon:mapIcon): Observable<string>{
      return this.http.post<string>(this.iconApiUrl, mapIcon, {
        headers: new HttpHeaders({
          'Content-Type': 'application/json',
          }),
        });  
      }

component.ts

onIconChange(e) {
    const reader = new FileReader();
    
    if(e.target.files && e.target.files.length) {
      const [file] = e.target.files;
      reader.readAsDataURL(file);
    
      reader.onload = () => {
        this.mapIcon.file = file; //(or even reader.result as string; as found in some example)
        this.mapIcon.name = file.name;
        this.mapIcon.active = true;
        //this.icon.file = file;
        /*this.uploadForm.patchValue({
          imgSrc: reader.result
        });*/
   
      };
    }
  }

the file field is defined as mediumblob in mysql.

The error I get is "Data integrity violation".

Can't understand where the error is..


Solution

  • The "Data integrity violation" error is caused by a failing constraint. This may be:

    • a foreign key constraint that is failing (referenced record does not exist)
    • a missing field value (on a field without a default value)
    • a null value where it is not allowed (the field is not nullable)

    You may enable debug mode ('debug' => true in the config) and look at the X-Exception-Message HTTP header of the response (using the Network tab of the Developer tools of your browser). It will contain the cause of the problem.

    NB: I am "mevdschee", the author of the PHP-CRUD-API.