1

I am using spring boot and I have simple form ,where there is upload option to upload the image.

<form>
    <div class="col-md-6">
        <input type='file' id="imgInp" />
        <img id="blah" src="#" alt="your image" width="200" height="200" />
    </div>
    <button type="submit" id="btn-add" class="btn btn-primary btn-lg">Add Employee
    </button>
</form>

When I upload the image,then it is changed into base 64 as below codes and it is manipulated in employee object and sent through AJAX post method.But I am getting error in spring boot side:

var imgObject;
$(document).ready(function() {

    $("#imgInp").change(function() {
        readURL(this);
    });

    function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();
            reader.onload = function(e) {
                $('#blah').attr('src', e.target.result);
                console.log("aaaa");
                imgObject = e.target.result;
                console.log(imgObject);
            }

            reader.readAsDataURL(input.files[0]);
        }
    }


    $('#btn-add').on('click', function() {

        //stop submit the form, we will post it manually.
        event.preventDefault();
        console.log("hitted");
        fire_ajax_submit();

    });

});

function fire_ajax_submit() {

    var employee = {
        "iNumber": $("#iNumber").val(),
        "fullName": $("#fullName").val(),
        "joinedDate": $("#joinedDate").val(),
        "position": $("#position").val(),
        "reportsTo": $("#reportsTo").val(),
        "cubicleNo": $("#cubicleNo").val(),
        "jobType": $("#jobType").val(),
        "imagObject": imgObject
    };

    console.log(employee);

    $.ajax({
        url: A_PAGE_CONTEXT_PATH + "/insert-emp",
        method: "post",
        contentType: "application/json",
        dataType: "json",
        data: JSON.stringify(employee),
        success: function(response) {
            console.log(response);
            alert("Successfully Saved!");
            window.location.reload(true);
        },
        error: function(response) {
            switch (response.status) {
                case 409:
                    alert("error");
            }
        }
    });

}

console.log(employee) is printed as:

enter image description here

The image is converted into base64. I tried to insert the image using AJAX.So, my Rest Api is:

@RestController
public class EmployeeController {

    @Autowired
    private EmployeeService empService;

    @PostMapping("/insert-emp")
    @ResponseBody
    public Employee createEmployee(@Valid @RequestBody Employee employee){
      return empService.saveEmployee(employee);
    }
}

My service class is:

@Service
public class EmployeeService {

    @Autowired
    private EmployeeRepository empRepository;

    public Employee saveEmployee(Employee employee){
        if(employee.getId()==0){
            empRepository.save(employee);
        }
        else{
            empRepository.save(employee);
        }
        return  employee;
    }

My repository class is:

@Repository
public interface  EmployeeRepository  extends JpaRepository<Employee,Integer> {
}

My model Employee.java class is:

@Entity
@Table(name = "employee")
public class Employee {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @NotBlank
    private String iNumber;

    @NotBlank
    private String fullName;

//    @NotBlank
    private String joinedDate;

    @NotBlank
    private String position;

    @NotBlank
    private String reportsTo;

    @NotBlank
    private String cubicleNo;

    @NotBlank
    private String jobType;

    private  byte[] imagObject;

    public Employee() {
    }

    //all getters and setters

}

But I am getting error as:

w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `byte[]` from String "image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAUEBAUEAwUFBAUGBgUGCA4JCAcHCBEMDQoOFBEVFBMRExMWGB8bFhceFxMTGyUcHiAhIyMjFRomKSYiKR8iIyL/2wBDAQYGBggHCBAJCRAiFhMWIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiL/wAARCAOWBmADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8]...[zUOSGGaKKfQfUUMSuR3NY3iCZ7WC3ky+3zQrBHKk8Hv9cUUUhMzv+Es8gLHLbsz/AN4P2/Kom8aQcj7NLke4ooplW0I9T1wvb20sbTQqZPm8vGTwcUtn4niS3WOaOVpAMMRg5P50UUE9BV8YWZyBDcDnH3V/xq3o2qLfmWP94SCWBfHQngUUUDGXGvwWskiSxSEx9SoH+NRr4hgctiKTAODwP8aKKQupONaiyN6Pg9MAf41Qi1mRb2Z3Zmi34CYHAoop20GbdvfLOrFVYY9ay4NUlW5l8470810C46YYj+lFFICWXUylwrHJiOBtxyDWgZRtVucHtRRTa0H0IzdBAcgmoReozHKtxRRSEthxuFwDtODQJAw70UUC6iH5Tx3prnauTk5oooH0IHnwxXHUAimbgeuaKKroJjzJ+74/WmRnI55zRRUCKMF68txIrqu0OVGOvBP+FXBz04ooprYZXEjNcNEcYA9KsoQqYxx0oopg9z//2Q==": Failed to decode VALUE_STRING as base64 (MIME-NO-LINEFEEDS): Illegal character ':' (code 0x3a) in base64 content; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `byte[]` from String "image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAUEBAUEAwUFBAUGBgUGCA4JCAcHCBEMDQoOFBEVFBMRExMWGB8bFhceFxMTGyUcHiAhIyMjFRomKSYiKR8iIyL/2wBDAQYGBggHCBAJCRAiFhMWIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiL/wAARCAOWBmADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8]...[zUOSGGaKKfQfUUMSuR3NY3iCZ7WC3ky+3zQrBHKk8Hv9cUUUhMzv+Es8gLHLbsz/AN4P2/Kom8aQcj7NLke4ooplW0I9T1wvb20sbTQqZPm8vGTwcUtn4niS3WOaOVpAMMRg5P50UUE9BV8YWZyBDcDnH3V/xq3o2qLfmWP94SCWBfHQngUUUDGXGvwWskiSxSEx9SoH+NRr4hgctiKTAODwP8aKKQupONaiyN6Pg9MAf41Qi1mRb2Z3Zmi34CYHAoop20GbdvfLOrFVYY9ay4NUlW5l8470810C46YYj+lFFICWXUylwrHJiOBtxyDWgZRtVucHtRRTa0H0IzdBAcgmoReozHKtxRRSEthxuFwDtODQJAw70UUC6iH5Tx3prnauTk5oooH0IHnwxXHUAimbgeuaKKroJjzJ+74/WmRnI55zRRUCKMF68txIrqu0OVGOvBP+FXBz04ooprYZXEjNcNEcYA9KsoQqYxx0oopg9z//2Q==": Failed to decode VALUE_STRING as base64 (MIME-NO-LINEFEEDS): Illegal character ':' (code 0x3a) in base64 content
 at [Source: (PushbackInputStream); line: 1, column: 143] (through reference chain: com.ashwin.vemployee.model.Employee["imagObject"])]

How can I handle this error?

Random guy
  • 883
  • 3
  • 11
  • 32

3 Answers3

2

This is not a standard approach. But try it.

@Entity @Table(name = "employee") 
public class Employee { 
@Id 
@GeneratedValue(strategy = GenerationType.IDENTITY)
 private Integer id;
 // Remaining fields 
@Transient
private String imageDecode;
}

From UI send your decoded data to this transient variable.

Once after the successful serialization convert that string to byte array[].

byte[] byte = imageDecode.getBytes();

Hope this will work.

GnanaJeyam
  • 2,780
  • 16
  • 27
0

The stack trace shows the exact problem. Yes you cannot deserialize the String to byte array. To make your JSON deserialize works you need to create custom deserializer.

Reference: https://www.baeldung.com/jackson-deserialization

GnanaJeyam
  • 2,780
  • 16
  • 27
0

Before sending remove:

data:image/jpeg;base64,

The parser only recognizes the bytes transformed with base64, the above is used so that the control can render it.

Edgardo Genini
  • 653
  • 5
  • 11