How to persist Image in Database Using Spring MVC3
controller:
public String postAdd(@ModelAttribute("employeeAttribute") @Valid Employee employee, BindingResult result,@RequestParam("file") MultipartFile file) throws Exception{
byte[] bFile=null;
System.out.println("File Name......"+file.getName());
if (!file.isEmpty()) {
bFile = new byte[(int) file.getSize()];
FileInputStream fileInputStream = new FileInputStream(file.getOriginalFilename());
fileInputStream.read(bFile);
fileInputStream.close();
}
employee.setImage(bFile);
employeeServiceImpl.add(employee);
}
Jsp Page:
<c:url var="saveEmp" value="/manam/mobee/employee/add"/>
<form:form modelAttribute="employeeAttribute" method="POST" action="${saveEmp}" enctype="multipart/form-data" >
<form:label path="image">Image</form:label>
<input type="file" name="file" id="file"></input>
here Iam sending the C:\Users\Public\Pictures\Sample Pictures\Desert Landscape.jpg file but
FileInputStream it will take only Landscape.jpg .
please suggest how to set full file path for FileInputStream.
Here I am getting java.io.FileNotFoundException: Forest.jpg (The system cannot find the file specified) Exception.
The original file name is the name of the file on the end-user’s machine. Your Spring MVC application runs on your server machine. You can’t use the original file name, hope to find the absolute file name on the end-user machine, and even less try to read the file using this name.
To get the contents of the uploaded file, use
MultipartFile.getBytes()orMultipartFile.getInputStream().