while fetching file from spring form I am getting null value and If I try this code for rest of fields i mean non multipart input types its working fine. while debugging I am getting null value from line. If I try to fetch image from existing folder i'e image under webapp and that url is able to display image in browser but not able to read value from files using browser and sorry for my bad english
edit if i comment the image code, application is working fine but when I introduce the code for image I'm getting error
MultipartFile file = domain.getImage(); //this is getting null
this is relevent code
controller
#RequestMapping(value = "/form", method = RequestMethod.GET)
public String formInputGet(Model model) {
model.addAttribute("domain", new Domain());
return "form";
}
#RequestMapping(value = "/form", method = RequestMethod.POST)
public String formInputPost(#ModelAttribute("domain") Domain domain, HttpServletRequest httpServletRequest) {
MultipartFile file = domain.getImage();
if (image== null)
throw new NullPointerException("unable to fetch "+file); //getting NPE everytime
String rootDirectory = httpServletRequest.getSession().getServletContext().getRealPath("/");
if (domain.getImage() != null && !domain.getImage().isEmpty())
try {
File path = new File(rootDirectory + "images\\" + domain.getFirstName() + ".png");
file.transferTo(path);
} catch (IllegalStateException | IOException e) {
e.printStackTrace();
}
repositiry.addToList(domain);
return "redirect:/";
}
form.jsp
<form:form modelAttribute="domain" enctype="multipart/form-data">
First Name<br>
<form:input path="firstName" />
<br>Last Name :<br>
<form:input path="lastName" />
<br>upload Image<br>
<form:input path="image" type="file" />
<hr>
<input type="submit">
</form:form>
dispatcherServlet
<mvc:annotation-driven />
<mvc:resources location="/images/" mapping="/images/**" />
<context:component-scan base-package="com" />
<bean id="multipartReslover"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10240000" />
</bean>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/views/" />
<property name="suffix" value=".jsp" />
</bean>
I added some extra code to find if I am getting domain as null came to be true. And I have no Idea how to solve that.
after adding check for file i'm getting error
java.lang.NullPointerException: unable to fetch : null
domain.java
public class Domain {
private String firstName;
private String lastName;
private MultipartFile image;
//getters and setters
NOTE any helpful answer if it have other way of working is welcomed too :)
any help is appreciated, thanks :)
you should do everything #kuhajeyen said and if getting image from domain object didnt go well you can try this
public String formInputPost(#ModelAttribute("domain") Domain domain,
#RequestParam("image") MultipartFile imagefile,
HttpServletRequest httpServletRequest ) {
imagefile.transferTo(path);
}
edit :- change method attribute to POST inside the form otherwise it will make a GET request.
<form:form modelAttribute="domain" method="post" enctype="multipart/form-data">
and replace your input type file with this line, i think there is some issues when trying to bind input type file with an object.
<input type="file" name="image" />
You need to tell the spring, how to resolve multipart file
add this bean
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="409600"/>
</bean>
And also it seems you have not mapped your action in form
<form:form modelAttribute="domain" enctype="multipart/form-data" action="xxxx/form">
....
</form:form>
There were two typos in my configuration file as they are
1) <mvc:resources location="/images/" mapping="/images/**" /> here mapping was supposed to be like mapping ="images/**"
2)File path = new File(rootDirectory + "images\\" + domain.getFirstName() + ".png"); here path is supposed to be as rootDirectory+"\\images\\"+.... instead
Related
I have a jsp index file wherein there is a simple login form and I check the values presented by the user at the controller and redirect them to the repectable jsp page which have other functionality.
Here's my index file:
<html>
</head> <body> <b><span class="heading">LOGIN USER</span></b> <div class="container">
<form action="login.html" method="Post">
<div class="form_style">
<input type="text" name="username" placeholder="Enter Username"/>
<input type="password" name="pwd" placeholder="Enter password"/>
<select name="dept">
<option>IT</option>
<option>Admin</option>
<option>HR</option>
<option>Marketing</option>
</select>
<input type="Submit" value="submit">
</div>
</form>
</div> </body>
</html>
Controller:
public class LoginController {
#RequestMapping("/login")
public ModelAndView loginResult(HttpServletRequest req,HttpServletResponse res) {
InfoEmployee inf = new InfoEmployee();
InfoManager inf2 = new InfoManager();
String uname=req.getParameter("username");
//Putting the username in the session object
String pwd=req.getParameter("pwd");
String dept = req.getParameter("dept");
String name1 = inf.getName();
String message1 = "Welcome "+name1;
String name2 = inf2.getName();
String message2 = "Welcome "+name2;
if(uname.equals(inf.getUsername())&&pwd.equals(inf.getPassword())&&dept.equals(inf.getDept()))
{
req.getSession().setAttribute("uname",inf.getName());
return new ModelAndView("employeeLoginResult", "message", message1);
}
else if(uname.equals(inf2.getUsername())&&pwd.equals(inf2.getPassword())&&dept.equals(inf2.getDept()))
{
req.getSession().setAttribute("uname",inf2.getName());
return new ModelAndView("adminLoginResult", "message", message2);
}
else
{
return new ModelAndView("RedirectTondex", "message","Sorry, username or password error");
}
}
Right now I have hardcoded the values for login in a java class which are InfoManager and InfoEmployee. I map the jsp to the other jsp's in the controller.
My Problem is that I want to redirect or include to the index file if nothing matches i.e. in the controller else statement.
If i give the reference of index in here, it only searches the WEB-INF/jsp directory as I have coded in the servlet dispatcher class like here
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
So I thought of two solutions
1 being that I could make a jsp to show the user some wrong stuff and redirect it to the index from there if it is possible.
2 redirect directly from the controller to the index and pass a message to index with the ModelAndView type method as the code mentioned above.
Any help or suggestion for the problem is appreciated.
Thank you in advance.
You can achieve it in several ways. One would be to return:
return new RedirectView("redirectedUrl");
Or you can use
return new ModelAndView("redirect:/abc.htm")
Or move the index file in web-inf/jsp and make it a JSP and redirect like:
return new ModelAndView("index")
I try to implement loading a photo and String object. Here is a declaration of my method.
#RequestMapping(method = RequestMethod.PUT, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public #ResponseBody ResponseEntity<UserWithPhoto> update(#RequestHeader(value="Access-key") String accessKey,
#RequestHeader(value="Secret-key") String secretKey,
#RequestPart("user") String string,
#RequestPart("photo") MultipartFile file) throws Exception
And this is my multi part resolver
<beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<beans:property name="maxUploadSize" value="10000000" />
</beans:bean>
And I havn't idea why I get
java.lang.IllegalStateException: Unable to process parts as no multi-part configuration has been provided
I always wrap multipart files in a POJO with other properties needed:
public class FileUpload {
private Long id;
private MultipartFile file;
// getters and setters
}
In my view:
<spring:url value="/myEndpoint" var="url_upload"/>
<form:form method="POST" enctype="multipart/form-data" commandName="fileUpload" action="${url_upload}" >
<form:hidden path="id" />
<input type="file" name="file" id="inputFile"/>
<input type="submit" value="Upload" />
</form:form>
And in the endpoint:
#RequestMapping(value = "/myEndpoint", method = RequestMethod.POST)
public String uploadFile(#ModelAttribute("fileUpload") FileUpload dto, Model uiModel) {
// Process file
}
Try adding this block code to your config:
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/index" />
<property name="suffix" value=".jsp" />
</bean>
and load your config on web.xml
I'm trying to upload an image following this and this tutorial but without using maven.
Here is my config related to upload:
ApplicationContext.xml
..
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10000000">
</property></bean>
My form:
<form:form
action="${ contextPath }admin/add-product"
method="POST" modelAttribute="addInventoryItemDto"
enctype="multipart/form-data">
<table>
....
<tr>
<td><b>Image:</b></td>
<td><input type="file" name="image" /></td>
</tr>
....
Controller
#RequestMapping( value = "/add-product", method = RequestMethod.POST )
public String addProduct(
#ModelAttribute( "addInventoryItemDto" ) #Valid AddInventoryItemDto inventoryDto,
#RequestParam( "image" ) MultipartFile img ) {
System.out.println("ContentType:" + img.getContentType());
return "admin/add-product";
}
I'm getting 404 Bad Request but when I remove the file related stuff in my Controller and form the request is properly sent to my controller
What I'm I missing or did wrong?
Try adding this tag:
<spring:url value="/add-product?${_csrf.parameterName}=${_csrf.token}" var="addItem"/>
And put this to the action attribute:
<form:form
action= "${addItem}"
method="POST" modelAttribute="addInventoryItemDto"
enctype="multipart/form-data" >
<table>
....
<tr>
<td><b>Image:</b></td>
<td><input type="file" name="image" /></td>
</tr>
....
If this isn’t working try also add the MultiPartHttpServletRequest object to your controller:
#RequestMapping( value = "/add-product", method = RequestMethod.POST )
public String addProduct(
#ModelAttribute( "addInventoryItemDto" ) #Valid AddInventoryItemDto inventoryDto,
MultiPartHttpServletRequest request,
#RequestParam( "image" ) MultipartFile img ) {
System.out.println("ContentType:" + img.getContentType());
return "admin/add-product";
}
I just moved the multipartResolver
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10000000">
</property></bean>
to my servlet-dispatcher configuration. Seems like that multipartResolver is part of spring MVC not the spring core
I'm using spring mvc. And I can't get param from url when method = post. But when I change method to GET, so I can get all param.
This is my form:
<form method="POST" action="http://localhost:8080/cms/customer/create_customer" id="frmRegister" name ="frmRegister" enctype="multipart/form-data">
<input class ="iptRegister" type="text" id="txtEmail" name="txtEmail" value="" />
<input class ="iptRegister" type="password" id="txtPassword" name="txtPassword" value="" />
<input class ="iptRegister" type="text" id="txtPhone" name="txtPhone" value="" />
<input type="button" id="btnRegister" name="btnRegister" value="Register" onclick="" style="cursor:pointer"/>
</form>
This is my controller:
#RequestMapping(value= "/create_customer", method = RequestMethod.POST)
#ResponseBody
public String createCustomer(HttpServletRequest request,
#RequestParam(value="txtEmail", required=false) String email,
#RequestParam(value="txtPassword", required=false) String password,
#RequestParam(value="txtPhone", required=false) String phone){
ResultDTO<String> rs = new ResultDTO<String>();
rs.setStatus(IConfig.SHOW_RESULT_SUCCESS_ON_MAIN_SCREEN);
try{
Customer c = new Customer();
c.setEmail(email);
c.setPassword(password);
c.setPhone(phone);
customerService.insert(c);
rs.setData("Insert success");
}catch(Exception ex){
log.error(ex);
rs.setStatus(IConfig.SHOW_RESULT_ERROR_ON_MAIN_SCREEN);
rs.setData("Insert failure");
}
return rs.toString();
}
How can I resolved this?
Spring annotations will work fine if you remove enctype="multipart/form-data".
#RequestParam(value="txtEmail", required=false)
You can even get the parameters from the request object .
request.getParameter(paramName);
Use a form in case the number of attributes are large. It will be convenient. Tutorial to get you started.
Configure the Multi-part resolver if you want to receive enctype="multipart/form-data".
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="250000"/>
</bean>
Refer the Spring documentation.
It also works if you change the content type
<form method="POST"
action="http://localhost:8080/cms/customer/create_customer"
id="frmRegister" name="frmRegister"
enctype="application/x-www-form-urlencoded">
In the controller also add the header value as follows:
#RequestMapping(value = "/create_customer", method = RequestMethod.POST, headers = "Content-Type=application/x-www-form-urlencoded")
When I want to get all the POST params I am using the code below,
#RequestMapping(value = "/", method = RequestMethod.POST)
public ViewForResponseClass update(#RequestBody AClass anObject) {
// Source..
}
I am using the #RequestBody annotation for post/put/delete http requests instead of the #RequestParam which reads the GET parameters.
You should use #RequestParam on those resources with method = RequestMethod.GET
In order to post parameters, you must send them as the request body. A body like JSON or another data representation would depending on your implementation (I mean, consume and produce MediaType).
Typically, multipart/form-data is used to upload files.
I keep getting this error when i do with my spring mvc code i am trying to do image upload using spring mvc what is the arguments I am missing.
org.springframework.web.util.NestedServletException: Request processing failed;
nested exception is java.lang.IllegalArgumentException: argument type mismatch
java.lang.IllegalArgumentException: argument type mismatch
...
My dispatcher servlet is
<context:component-scan base-package="com.ImageUploadSpring.Controller" />
<!-- <bean id="simpleHandler" class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/> -->
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver" />
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/Upload.html">FileUpload</prop>
</props>
</property>
</bean>
<bean id="FileUpload" class="com.ImageUploadSpring.Controller.FileUpload">
<property name="commandName" value="ImageUpload"/>
<property name="commandClass" value="com.ImageUploadSpring.Bean.UploadItem"/>
<property name="formView" value="ImageUpload"/>
<property name="successView" value="message"/>
</bean>
<bean id="FileUpload" class="com.ImageUploadSpring.Controller.FileUpload"></bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".html" />
</bean>
controller class is
public class FileUpload extends SimpleFormController{
#RequestMapping(value = "/Upload.html", method = RequestMethod.POST)
protected ModelAndView onSubmit(HttpServletRequest request,
HttpServletResponse response, Object command, BindException errors,HttpSession session) {
System.out.println("inside submit method");
try{
UploadItem item=(UploadItem)command;
MultipartFile file = item.getFile();
InputStream inputStream = null;
OutputStream outputStream = null;
if (file.getSize() > 0) {
inputStream = file.getInputStream();
outputStream = new FileOutputStream("D:/UploadedFiles/Images/"
+ file.getOriginalFilename());
System.out.println(file.getOriginalFilename());
int readBytes = 0;
byte[] buffer = new byte[8192];
while ((readBytes = inputStream.read(buffer, 0, 8192)) != -1) {
outputStream.write(buffer, 0, readBytes);
}
outputStream.close();
inputStream.close();
session.setAttribute("uploadFile", "D:/UploadedFiles/Images/"
+ file.getOriginalFilename());
}
}catch (Exception e) {
e.printStackTrace();
}
return new ModelAndView("message");
}
#Override
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder)
throws ServletException {
binder.registerCustomEditor(byte[].class, new ByteArrayMultipartFileEditor());
}
And my html page is
<form name="ImageUpload" action="/ImageUploadSpring/service/Upload.html" method="POST" enctype="multipart/form-data">
<div>
Select images:
<input type="text" id="box"/>
<input type="file" id="UploadFile" name="UploadFile" onchange="CopyMe(this,'box');" accept="image/*" size="40" style="width: 91px;" multiple />
<br><br>
<input type="submit" value="Upload" /><br><br>
</div>
</form>
Try this:
protected ModelAndView onSubmit(HttpServletRequest request,HttpServletResponse response,#RequestParam(value="UploadFile") MultipartFile image, BindException errors,HttpSession session)
While defining <input type="file"> you have specified the name name="UploadFile". Whereas in your UploadItem command object the file attribute is file (guessing from item.getFile()). Are you sure you are correctly mapping the filename?
Please refer to this tutorial for working tutorial on Spring MVC File Upload
this tutorial http://www.journaldev.com/2573/spring-mvc-file-upload-example-tutorial-single-and-multiple-files also works well for me. it is quite simple.
the important is when you use
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="100000" />
</bean>
,
don't forget to add commons-fileupload to your pom dependencies.