Nikil Karanjit Nikil Karanjit - 28 days ago 7
Java Question

the controller is saving the image but the image cannot be found in the desired folder ..is my controller correct

@Controller
@RequestMapping(value = "/admin/room")

public class Roomcontroller {

@Autowired
private RoomService roomService;

@RequestMapping(method = RequestMethod.GET)
public String index(ModelMap map) throws SQLException {
map.addAttribute("Room", roomService.getAll());
return "admin/room/index";
}

@RequestMapping(value = "/addroom", method = RequestMethod.GET)
public String addRoom() throws SQLException {
return "admin/room/addroom";
}


@RequestMapping(value = "/editroom/{ro_id}", method = RequestMethod.GET)
public ModelAndView edit(@PathVariable("ro_id") int ro_id) throws SQLException {
ModelAndView mv = new ModelAndView("admin/room/editroom");
mv.addObject("Room", roomService.getById(ro_id));
return mv;
}

@RequestMapping(value = "/deleteroom/{ro_id}", method = RequestMethod.GET)
public String delete(@PathVariable("ro_id") int ro_id) throws SQLException {
roomService.delete(ro_id);
return "redirect:/admin/room";
}


this portion of the code is used for saving image and other entities but I am not able to see the image stored in desired folder

@RequestMapping(value = "/save", method = RequestMethod.POST)

public String save(@RequestParam("roomType") String roomType,
@RequestParam("roomDescription") String roomDescription, @RequestParam("roomNumber") int roomNumber,
@RequestParam("file") MultipartFile multipartFile, HttpServletRequest req) throws SQLException, IOException {

Room room = new Room();
room.setRoom_type(roomType);
room.setRoom_description(roomDescription);
room.setRoom_number(roomNumber);

// TO DO : Save room, fetch the id of saved room and set it through
// setter in above object.

if(room.getRo_id()==0){

String serverRootPath = req.getServletContext().getRealPath("");
System.out.println(serverRootPath);

// You can change the directory.
File roomImageDirectory = new File(serverRootPath + "D:\\Hotels\\ploadedImages");

if (!roomImageDirectory.exists()) {
roomImageDirectory.mkdirs();
}
String[] fileNameToken = multipartFile.getOriginalFilename().split("\\.");

// You can change file name to be saved.
String newFileName = "room-" + room.getRo_id() + "." + fileNameToken[fileNameToken.length - 1];

File roomImage = new File(roomImageDirectory, "/" + newFileName);
roomImage.createNewFile();
multipartFile.transferTo(roomImage);
room.setImage(newFileName);
roomService.insert(room);
}

else{
roomService.update(room);
}
return "redirect:/admin/room";
}
}

Answer

According to your code, you want to save your file under D:\\Hotels\\ploadedImages. So you don't need to use req.getServletContext().getRealPath(""). Just change your code like this

File roomImageDirectory = new File("D:\\Hotels\\ploadedImages");
...
File roomImage = new File(roomImageDirectory, "/" + newFileName);

I prefer File.separator instead of using / or \\

Comments