I am working in spring mvc project.
I am able to run my project in my local without any issues. I did a page for file upload using controller.
While I used this with production, I am not able to get the results and getting the error
"org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'userId' is not present
my code : (I am getting this user Id in upload screen)
#Resource
private UserService userService;
#Override
protected ModelAndView handleRequestInternal(HttpServletRequest request,
HttpServletResponse response) throws Exception {
Long userId = userService.getLoggedInUser(request).getId();
ModelAndView modelAndView = new ModelAndView(UploadDocView.uploadmain);
modelAndView.addObject("userId", userId);
return modelAndView;
}
upload jsp
<form method="POST" enctype="multipart/form-data" action="upload.htm">
File to upload:
<input type="file" name="file"><br />
<input type="hidden" name="userId" value="${userId}"><br /> <br />
<input type="submit" value="Upload">
</form>
FileUploadController
#Controller
public class FileUploadController {
#Resource
private CollectionsRepository collectionsRepository;
#RequestMapping(value="/upload", method=RequestMethod.GET)
public #ResponseBody String provideUploadInfo() {
return "You can upload a file by posting to this same URL.";
}
#RequestMapping(value="/upload.htm", method=RequestMethod.POST)
public ModelAndView handleFileUpload(#RequestParam("userId") String userId, #RequestParam("file") MultipartFile file){
if (!file.isEmpty()) {
try {
String filePath = "/home/ubuntu/analyzer/LOS/";
byte[] bytes = file.getBytes();
File newFile = new File(filePath+""+file.getOriginalFilename());
BufferedOutputStream stream =
new BufferedOutputStream(new FileOutputStream(newFile));
stream.write(bytes);
stream.close();
List<BankStatementError> errorList = new ArrayList<BankStatementError>();
Excelsheetreader esr = new Excelsheetreader();
List<String> listaddSN = esr.GetCalculation(Long.parseLong(userId), filePath+""+file.getOriginalFilename());
newFile.delete();
for (int i = 0; i < listaddSN.size(); i++) {
String bank = listaddSN.get(i);
BankStatementError error = collectionsRepository.getErrorByBank(bank);
errorList.add(error);
}
ModelAndView modelAndView = new ModelAndView(UploadDocView.uploadsuccess);
modelAndView.addObject("errorList", errorList);
return modelAndView;
} catch (Exception e) {
ModelAndView modelAndView = new ModelAndView(UploadDocView.uploadexecption);
return modelAndView;
}
} else {
ModelAndView modelAndView = new ModelAndView(UploadDocView.uploadempty);
return modelAndView;
}
}
}
The problem is userId comes as null, which is getting for upload screen, I think. But not sure. Can anyone point me a right way in this?
Related
#PostMapping("/post")
public String write(#RequestParam("file") MultipartFile files, BoardDto boardDto) {
try {
String origFilename = files.getOriginalFilename();
String filename = new MD5Generator(origFilename).toString();
String savePath = System.getProperty("user.dir") + "\\files";
if (!new File(savePath).exists()) {
try {
new File(savePath).mkdir();
} catch(Exception e){
e.getStackTrace();
}
}
String filePath = savePath + "\\" + filename;
files.transferTo(new File(filePath));
FileDto fileDto = new FileDto();
fileDto.setOrigFilename(origFilename);
fileDto.setFilename(filename);
fileDto.setFilePath(filePath);
Long fileId = fileService.saveFile(fileDto);
boardDto.setFileId(fileId);
boardService.savePost(boardDto);
} catch(Exception e) {
e.printStackTrace();
}
return "redirect:/";
}
if (!new File(savePath).exists()) {
^
constructor File.File(Long,String,String,String) is not applicable
Description: I am working on a file upload project. but it's not working. File is just entity class and It's someone else's code. the guy worked fine but I'm not
You can try to rewrite this code using Files API.
For example: ...if (Files.notExists(Paths.get(savePath))) {...
It looks like you create too many File objects.
You can upload a file to a Spring controller using logic as follows:
Basic HTML that sends a file to a /upload controller:
<p>Upload an image</p>
<form method="POST" onsubmit="myFunction()" action="/upload" enctype="multipart/form-data">
<input type="file" name="file" /><br/><br/>
<input type="submit" value="Submit" />
</form>
<div>
Here is the controller:
// Upload a file.
#RequestMapping(value = "/upload", method = RequestMethod.POST)
#ResponseBody
public ModelAndView singleFileUpload(#RequestParam("file") MultipartFile file) {
try {
byte[] bytes = file.getBytes();
String name = file.getOriginalFilename() ;
// DO something with the file.
} catch (IOException e) {
e.printStackTrace();
}
return new ModelAndView(new RedirectView("photo"));
}
how to send data from the form view to the backend? I want to use the collected data to create a JSON request.
#Controller
public class ControllerClass {
Connect connect = new Connect();
#RequestMapping(value = "/Search", method = RequestMethod.GET)
public ModelAndView showForm() {
return new ModelAndView("Forms", "FlightDTO", new FlightDTO());
}
#RequestMapping(value = "/connect", method = RequestMethod.POST)
public String submit(#Valid #ModelAttribute("FlightDTO") FlightDTO flightDTO,
BindingResult result, ModelMap model) {
if (result.hasErrors()) {
return "error.jsp";
}
return connect.connect();
}
}
View class collecting data.
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Getting Started: Handling Form Submission</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Form</h1>
<form action="#" th:action="#{/connect}" th:object="${FlightDTO}" method="post">
<p>Orgin: <input type="text" th:field="*{Origin}" /></p>
<p>Departure: <input type="text" th:field="*{Departure}" /></p>
<p>DateFrom: <input type="text" th:field="*{DateFrom}" /></p>
<p>DateTo: <input type="text" th:field="*{DateTo}" /></p>
<p>Currency: <input type="text" th:field="*{Currency}" /></p>
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
</body>
</html>
Class responsible for consume data JSON.
public class Connect {
public String connect() {
String output = null;
try {
UrlBuilder urlBuilder = new UrlBuilder();
urlBuilder.ulr();
System.out.println("URL String : " + urlBuilder.ulr());
URL url = new URL(urlBuilder.ulr());
HttpURLConnection conn = (HttpURLConnection) url.openConnection() ;
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP Error code : " + conn.getResponseCode());
}
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
output = response.toString();
} catch (Exception e) {
System.out.println("Exception Flight:- " + e);
}
return output;
}
}
Class that is responsible for collecting data from the view
public class FlightDTO {
private String dateFrom;
private String dateTo;
#Size(min = 2, max = 10)
private String origin;
#Size(min = 2, max = 10)
private String departure;
#Size(min = 2, max = 4)
private String currency;
My URL builder Class responsible for build request.
public class UrlBuilder extends FlightDTO {
private String key = "47c5ebee552ce27c902e7521b6ef3858";
public String ulr( ) {
String connectUrlString =
"http://api.travelpayouts.com/v1/prices/cheap?origin="
+ getOrigin() + "&destination=" + getDeparture() +
"&depart_date=" + getDateFrom() +
"¤cy=" + getCurrency() +
"&return_date=" + getDateTo() +
"&token=" + key;
return connectUrlString ;
}
}
I tried to solve my problem in many ways. Unfortunately to no avail, that's why I decided to create a thread. I could not find a similar problem. I was probably looking for a bad one. However, I do not know how to google
I get null response :
http://api.travelpayouts.com/v1/prices/cheap?origin=null&destination=null&depart_date=null¤cy=null&return_date=null&token=47c5ebee552ce27c902e7521b6ef3858
Above code will not work as you are creating new UrlBuilder object which will not have any values instead of passing flightDTO object from the controller.
Controller
#RequestMapping(value = "/connect", method = RequestMethod.POST)
public String submit(#Valid #ModelAttribute("FlightDTO") FlightDTO flightDTO,
BindingResult result, ModelMap model) {
if (result.hasErrors()) {
return "error.jsp";
}
return connect.connect(flightDTO); //passing flightDTO object received from form
}
Connect
public String connect(FlightDTO flightDTO) { //Added new parameter to recevice flightDTO
String output = null;
try {
UrlBuilder urlBuilder = new UrlBuilder();
urlBuilder.setOrigin(flightDTO.getOrigin());
urlBuilder.setDestination(flightDTO.getDestination());
urlBuilder.setDateFrom(flightDTO.getDateFrom());
urlBuilder.setDateTo(flightDTO.getDateTo());
......//Set other required values
urlBuilder.ulr();
System.out.println("URL String : " + urlBuilder.ulr());
......//other code
}
}
#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";
}
}
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 \\
probably you are constructing a wrong path
try,
String pathToUpload = req.getServletContext().getRealPath("/fileuploads");
File f = new File(pathToUpload);
if(f.exists() && !f.isDirectory()) {
f.mkdir();
}
String orgName = multipartFile.getOriginalFilename();
String filePath = pathToUpload + orgName;
File dest = new File(pathToUpload);
file.transferTo(dest);
you should see file created inside root folder of your application context.
I would like to check if session not equals to null,then some button or link will be hidden.Or any other better way to do that?
This is my controller :
#RequestMapping(value = "/signin", method = RequestMethod.GET)
public Object signIn(HttpSession session) {
MemberSignIn signIn = new MemberSignIn();
signIn.setLoginId((String) session.getAttribute("loginId"));
return new ModelAndView("member/signin").addObject("signIn", signIn);
}
#RequestMapping(value = "/signin", method = RequestMethod.POST)
public Object signIn(#ModelAttribute MemberSignIn memberSignIn, HttpSession session, RedirectAttributes redirectAttributes) {
try {
Session s = memberService.signIn(memberSignIn);
session.setAttribute("loginId", memberSignIn.getLoginId());
session.setAttribute("token", s.getToken());
session.setAttribute("memberId", s.getMemberId());
MemberDetail detail = memberService.detail(s.getMemberId());
session.setAttribute("name", detail.getName());
return "redirect:/index";
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
return new ModelAndView("member/signin")
.addObject("signIn", memberSignIn)
.addObject("error", e.getMessage());
}
}
HTML:
<li>Sign In</li>
<li>Sign Up</li>
I have a BLOB type image in mysql database and I want to show the image on the jsp. I am using Hibernate and Spring MVC. This is my Model class:
#Repository
#Entity
#Table(name = "foto")
public class Image {
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "fk_id_users", nullable = false)
private Users user;
#Id
#Column(name = "id_foto")
#GeneratedValue(strategy = GenerationType.AUTO)
private int id_foto;
#Column(name = "tipo")
private String tipo;
#Column(name = "size")
private String size;
#Column(name = "nome")
private String nome;
#Column(name = "image")
private byte[] image;
//Getters and Setters
this is my controller:
#Controller
#SessionAttributes("UserSession")
public class LoginController {
#Autowired
private UsersService usersService;
#RequestMapping(value = "loginUsers", method = RequestMethod.POST)
public ModelAndView loginUsers(HttpServletRequest request,#RequestParam("username") String username,
#RequestParam("password") String password) {
Users user = usersService.loginUsers(username, password);
if( user == null ) {
ModelAndView MV = new ModelAndView("login");
MV.addObject("erroreLogin", "username e/o password errati");
return MV;
} else if ( user.getAmministratore() == false ){
request.getSession().setAttribute("UserSession",user);
ModelAndView mav = new ModelAndView("homeUtente");
mav.addObject("galleria", usersService.getAllFoto());
return mav;
} else {
request.getSession().setAttribute("UserSession",user);
ModelAndView mav = new ModelAndView("utenti");
mav.addObject("lista", usersService.getAllUtenti());
return mav;
}
}
#RequestMapping(value = "logout", method = RequestMethod.GET)
public ModelAndView logout(HttpServletRequest request) {
request.getSession().invalidate(); //invalido i dati presenti in sessione
return new ModelAndView("login");
}
}
and in my jsp I use this for show my image from Image List because each user have a gallery to display:
<img alt="Kangoo_image" src="data:image/jpeg;base64,${galleria.image}" />
when i'm trying to display it in my jsp.It is showing something binary like [B#59e73b47. how can i display the image here in jsp?
To show the image on JSP without storing to filesystem and linking to it, you'll have to do a Base64 encoding of the byte array. Easily done by following lines
byte[] encodeBase64 = Base64.encodeBase64(usersService.getAllFoto());
String base64Encoded = new String(encodeBase64, "UTF-8");
mav.addObject("galleria", usersService.getAllFoto());
Both IOUtils and Base64 are from org.apache.commonsEndFragment
this appends beacause galleria.image returns a byte[] type, and on the resulting html of the jsp appear the byte[].toString() value. exactly [B#59e73b47.
you should use something like:
<img alt="Kangoo_image" src="data:image/jpeg;base64,new String(${galleria.image})" />
or
<img alt="Kangoo_image" src="/getImage/${galleria.id_foto}" />
and in in the getImage controller somthing like this
#Autowired
private HttpServletRequest request;
#RequestMapping("/getImage/*")
public void getImage(ModelMap model, HttpServletResponse response)
throws IOException {
requestUri = requestUri.substring((request.getContextPath() + "/getImage/")
.length());
Image image = DAO.findById(requestUri);
String requestUri = request.getRequestURI();
InputStream is = new ByteArrayInputStream(image.getImage());
response.setContentType("image/jpeg");
String name = image.getName() + ".jpeg";
String attachment = "inline; filename=" + name;
response.setHeader("content-Disposition", attachment);
response.setContentLength((int) baos.toByteArray().length);
IOUtils.copy(is, response.getOutputStream());
response.flushBuffer();
is.close();
}
#Controller
#SessionAttributes("UserSession")
public class LoginController {
#Autowired
private UsersService usersService;
#RequestMapping(value = "loginUsers", method = RequestMethod.POST)
public ModelAndView loginUsers(HttpServletRequest request,#RequestParam("username") String username,
#RequestParam("password") String password) {
Users user = usersService.loginUsers(username, password);
if( user == null ) {
ModelAndView MV = new ModelAndView("login");
MV.addObject("erroreLogin", "username e/o password errati");
return MV;
} else if ( user.getAmministratore() == false ){
request.getSession().setAttribute("UserSession",user);
ModelAndView mav = new ModelAndView("homeUtente");
byte[] encodeBase64 = Base64.encode(usersService.getAllFoto());
String base64Encoded = new String(encodeBase64, "UTF-8");
mav.addObject("userImage", base64Encoded )
return mav;
} else {
request.getSession().setAttribute("UserSession",user);
ModelAndView mav = new ModelAndView("utenti");
mav.addObject("lista", usersService.getAllUtenti());
return mav;
}
}
#RequestMapping(value = "logout", method = RequestMethod.GET)
public ModelAndView logout(HttpServletRequest request) {
request.getSession().invalidate(); //invalido i dati presenti in sessione
return new ModelAndView("login");
}
}
and in jsp code use this code to display image
<img src="data:image/jpeg;base64,${userImage}" />