I am trying to upload photo in my local disk.So,I am using spring boot.And I have used MultipartFile
to upload the file.So,I have a basic form and when I click the submit button then the POST method of AJAX is called.
I have used <input type="file" name="files" />
to upload the file.
<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>
And here comes my javascript part which is handling the form data as:
$(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");
}
}
});
}
The JSON data I am sending looks like:
The Rest Api is :
@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);
}
}
}
My model class Employee.java 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;
@Transient
private MultipartFile files;
public Employee() {
}
//all getters and setters
}
I am getting error when I am submitting:
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of org.springframework.web.multipart.MultipartFile
(no Creators, like default construct, exist): abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information
at [Source: (PushbackInputStream); line: 1, column: 141] (through reference chain: com.ashwin.vemployee.model.Employee["files"])