Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
249 views
in Technique[技术] by (71.8m points)

javascript - 图像未在Spring Boot中插入(Image not being insert in spring boot)

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

(我使用的是Spring Boot,它的表单很简单,有上传选项可以上传图像。)

<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:

(当我上传图像时,然后将其按以下代码更改为base 64,并在员工对象中进行操作并通过AJAX post方法发送。但是在Spring Boot端出现错误:)

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:

(console.log(employee)打印为:)

在此处输入图片说明

The image is converted into base64.

(该图像将转换为base64。)

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

(我试图使用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);
    }
}

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:

(我的模型Employee.java类是:)

@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?

(如何处理此错误?)

  ask by Karki Ashwin translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...