나는 봄 부팅을 사용하고 있으며 이미지를 업로드하는 업로드 옵션이있는 간단한 양식이 있습니다.
<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>
이미지를 업로드하면 아래 코드와 같이 base64로 변경되고 직원 객체에서 조작되어 AJAX post 메소드를 통해 전송됩니다.하지만 스프링 부트 측에서 오류가 발생합니다.
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)
는 다음과 같이 print됩니다.
이미지는 base64로 변환됩니다.AJAX를 사용하여 이미지를 삽입하려고했는데 내 Rest Api는 다음과 같습니다.
@RestController
public class EmployeeController {
@Autowired
private EmployeeService empService;
@PostMapping("/insert-emp")
@ResponseBody
public Employee createEmployee(@Valid @RequestBody Employee employee){
return empService.saveEmployee(employee);
}
}
내 서비스 class는 다음과 같습니다.
@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;
}
내 저장소 class는 다음과 같습니다.
@Repository
public interface EmployeeRepository extends JpaRepository<Employee,Integer> {
}
내 모델 Employee.java class는 다음과 같습니다.
@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
}
하지만 다음과 같은 오류가 발생합니다.
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"])]
이 오류를 어떻게 처리 할 수 있습니까?