在春季启动时无法构造`org.springframework.web.multipart.MultipartFile`错误的实例

时间:2019-12-02 17:01:57

标签: java ajax spring spring-boot

我正在尝试将照片上传到本地磁盘中。因此,我正在使用Spring Boot。并且我已经使用MultipartFile来上传文件。因此,我具有基本的表单,当我单击提交按钮时然后调用AJAX的POST方法。

我已使用<input type="file" name="files" />上传文件。

<form method="POST" enctype="multipart/form-data" id="fileUploadForm">

    <div class="col-md-6">
        <input type="file" name="files" />
        <br/>
        <br/>

    </div>

    <label>iNumber</label>
    <input name="iNumber" name="iNumber" id="iNumber" type="text" class="form-control" required="required" />

    <label>Full Name:</label>
    <input name="fullName" name="fullName" id="fullName" type="text" class="form-control" required="required" />

    <label>Joined Date</label>
    <input name="joinedDate" id="joinedDate" type="text" class="form-control" required="required" />

    <label>Position</label>
    <input name="position" id="position" type="text" class="form-control" required="required" />

    <label>Reports To</label>
    <input name="reportsTo" id="reportsTo" type="text" class="form-control" required="required" />

    <label>Cubicle No</label>
    <input name="cubicleNo" id="cubicleNo" type="text" class="form-control" required="required" />

    <label>Job type</label>
    <input name="jobType" id="jobType" type="text" class="form-control" required="required" />

    <input type="submit" value="Submit" id="btnSubmit" />

</form>

这是我的javascript部分,该部分将表单数据处理为:

$(document).ready(function () {

        $('#btnSubmit').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 form = $('#fileUploadForm')[0];
console.log(form);
  var data = new FormData(form);
console.log(data);
 data.append("CustomField", "This is some extra data, testing");
 console.log(data);
var employee={
      "iNumber":$("#iNumber").val(),
       "fullName":$("#fullName").val(),
       "joinedDate":$("#joinedDate").val(),
         "position":$("#position").val(),
       "reportsTo":$("#reportsTo").val(),
        "cubicleNo":$("#cubicleNo").val(),
      "jobType":$("#jobType").val(),
      "files":data
};

    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");
                        }
                    }
                });

}

我发送的JSON数据如下:

enter image description here

其余Api是:

@RestController
public class EmployeeController {

    @Autowired
    private EmployeeService empService;


    //Save the uploaded file to this folder
    private static String UPLOADED_FOLDER = "F://temp//";

    @PostMapping("/insert-emp")
    @ResponseBody
    public ResponseEntity<?> createEmployee(@Valid @RequestBody Employee employee) {
        MultipartFile uploadfile=employee.getFiles();
        System.out.println("entered here");
        if (uploadfile.isEmpty()) {
            return new ResponseEntity("please select a file!", HttpStatus.OK);
        }

        try {

            saveUploadedFiles(Arrays.asList(uploadfile));

        } catch (IOException e) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
        return new ResponseEntity("Successfully uploaded - " +
                uploadfile.getOriginalFilename(), new HttpHeaders(), HttpStatus.OK);
    }

    //save file
    private void saveUploadedFiles(List<MultipartFile> files) throws IOException {

        for (MultipartFile file : files) {

            if (file.isEmpty()) {
                continue; //next pls
            }

            byte[] bytes = file.getBytes();
            Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
            Files.write(path, bytes);

        }

    }
}

我的模型类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;

    @Transient
    private MultipartFile files;

    public Employee() {
    }
//all getters and setters
}

提交时出现错误:

com.fasterxml.jackson.databind.exc.InvalidDefinitionException:无法构造org.springframework.web.multipart.MultipartFile的实例(不存在创建者,如默认构造一样):抽象类型要么需要映射为具体类型,要么具有自定义反序列化器,或包含其他类型信息  在[来源:(PushbackInputStream);行:1,列:141](通过参考链:com.ashwin.vemployee.model.Employee [“ files”])

0 个答案:

没有答案