I am trying to upload files using Spring CommonsMultipartResolver however the controller is not recognised. I get this errror message: "The requested resource (/WebIDE/WEB-INF/views/file/upload.jsp) is not available."
I have added commons-fileupload-1.2.2.jar and commons-io.1.3.2.jar in my library. I have added the following in my application context:
<context:component-scan base-package="org.webide.mvc" />
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- specify maximum file size in bytes -->
<property name="maxUploadSize" value="100000"/>
</bean>
I'm using Pojo as my controller:
#Controller
#RequestMapping (value = "/file")
public class FileController {
#RequestMapping (value = "/upload")
public String uploadFile(#RequestParam("file") CommonsMultipartFile file){
if (!file.isEmpty()){
byte fileBytes[] = file.getBytes();
return "mainView";
}else{
return "errorView";
}
}
My html is quite simple at the moment:
<form method="post" action="file/upload" enctype="multipart/form-data">
<input type="text" name="name"/>
<input type="file" name="file"/>
<input type="submit"/>
</form>
Could you please let me know if I am missing something?
Thanks
The main URL was http://localhost:8084/WebIDE/, then action="/file/upload" should send request to class marked with #Controller. I put a breakpoint and it was not picking up the controller at all.
I had to change my spring configuration to copy everything specified in application context (see above) to dispatcher servlet mvc-config.xml, and also change the way I was declaring them so that the context is the parent of mvc-config.xml
Looks like it did the trick! :)
Thanks again for your help and suggestions.
Related
I am trying to add feature of uploading excel to my spring boot application.
jsp:
<form action="/uploadpoifile/truepoi" method="post" enctype="multipart/form-data">
<input type="file" name="excelfile" />
<input type="submit" value="Upload" />
</form>
bean:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"/>
<property name="maxInMemorySize" value="409600"/>
<property name="maxUploadSize" value="200000000"/>
</bean>
controller:
#Controller
#RequestMapping("/uploadpoifile")
public class QcUploadPoiFileController {
#ResponseBody
#RequestMapping(value = "/{poiType}", method = RequestMethod.POST)
void update(#RequestParam(value = "excelfile") CommonsMultipartFile file, #PathVariable(value = "poiType") String poiType){...}
}
After I selected excel I click upload and see error message:
Required CommonsMultipartFile parameter 'excelfile' is not present
What do I wrong?
Is it possible to handle a form using Spring annotation #ModelAttribute without using the Spring tag <form:form...>. I saw this way to do but it seems complex with using Thymeleaf (I don't know anything about it).
Spring is supposed to be a non-intrusive framework so is there an alternate solution to my problem?
If you build your form using Spring tags, it will be converted to HTML. Run your project and check the source code of your JSP site. Spring tags just make things a bit easier for a coder. For example
<form:form modelAttribute="newUser" action="/addUser" method="post">
<form:input path="firstName" />
<form:input path="lastName" />
<button type="submit">Add</button>
</form:form>
will be converted to HTML
<form id="newUser" action="/addUser" method="post">
<input id="firstName" name="firstName" type="text" value="" />
<input id="lastName" name="lastName" type="text" value="" />
<button type="submit">Add</button>
</form>
In Controller you add a data transfer object (DTO) to Model, for example
#RequestMapping(value = "/index", method = RequestMethod.GET)
public ModelAndView homePage() {
ModelAndView model = new ModelAndView();
model.addObject("newUser", new User());
model.setViewName("index");
return model;
}
and receive the form data
#RequestMapping(value = "/addUser", method = RequestMethod.POST)
public ModelAndView addUser(
#ModelAttribute("newUser") User user) { ... }
Using Spring tags is totally optional as long as the naming of the form fields is exactly the same as in your bean object (here User class) and model.
Use JSp as suggested in the comment section above.
First you must add the following depency to your pom (or its equivalent for gradle)
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.4</version>
<scope>provided</scope>
</dependency>
Also, your jsp's should be placed inside your web-inf folder.
Your application.properties should look like this:
spring.mvc.view.prefix: /WEB-INF/jsp/
spring.mvc.view.suffix: .jsp
We upgraded the code from jboss 4 to wildfly 9 and upgraded spring 2.5 to spring 3.0 and everything is working good.
While we are uploading files less than 150kb using MultipartFile, it is working fine. but when file size exceeds 150kb all request parameters and multipartfile becomes null.
We are using Spring 3.2, java 8, wildfly 9.0
i am attaching my code for your reference
Controller
#Controller
#MultipartConfig(fileSizeThreshold=1024*1024*2, // 2MB
maxFileSize=1024*1024*10, // 10MB
maxRequestSize=1024*1024*50)
public class MyPortFolioController{
#RequestMapping(value = UrlPrefix.consumer+"/myportfolio.htm", method = RequestMethod.POST)
public ModelAndView uploadFile(#ModelAttribute Portfolio portfolio, BindingResult result,
Model model,#RequestParam("file")MultipartFile f,HttpServletRequest request,HttpServletResponse response, HttpSession session
jsp file
<form:form modelAttribute="portfolio" method="POST" id="myuplod" enctype="multipart/form-data" name="portfolioform">
<form:select path="protfolioTypeIdentifier" id="selectType" cssClass="form-control" cssStyle="width:auto;">
<form:option value="0">Select one</form:option>
<form:options items="${portfolioType}"
itemValue="protfolioTypeIdentifier"
itemLabel="portFolioTypeName" />
</form:select>
<input type="file" name="file" class="btn btn-primary" onchange="dwr.util.byId('upportf').style.display='block';"/>
<input type="submit" value="Upload" class="btn btn-warning" id="upportf" name="Upload" onclick="displayLoaderScreen();"/>
</form:form>
applicationContext.xml
<bean id="multipartResolvder" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" >
<!-- 25 mb max -->
<property name="maxUploadSize" value="26214400"/>
</bean>
please help
Files with size "maxInMemorySize " are stored in memory, otherwise they will be stored in disk directly. Default is 10KB (10240 bytes)
Add these line in spring.xml
Add these line in spring.xml
<!-- mutipart upload configuration -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- max upload size in bytes 2MB-->
<property name="maxUploadSize" value="2097152" />
<!-- max size of file in memory (in bytes) 2MB -->
<property name="maxInMemorySize" value="2097152" />
</bean>
Hello I have a form input button as follows :
<form:input path="creationUsr.lastName" type="text" name="creationUsr.lastName" id="creationUsr.lastName" class="login-text" placeholder="<spring:message code='tile.form.lastName'/>" value=""/>
Here is my spring context locale setting :
<mvc:interceptors>
<bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"/>
</mvc:interceptors>
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
<property name="defaultLocale" value="en" />
</bean>
If I put this out of form tag :
<spring:message code='tile.form.lastName'/>
The value is as I should be.
I have a way around this but it's kind of ugly. I could revert to normal forms without using spring and regular <input type="text" name="lastname"> instead of <form:input .. and then serialize form to json and do a post with javascript.
I'm sure there must be a way to do this with spring mvc.
You can't use a JSP tag inside an attribute of another JSP tag. To do what you want, save the message in a page-scope attribute, and use the EL to pass the message to the input tag:
<spring:message code='tile.form.lastName' var="lastNameMessage"/>
<form:input path="creationUsr.lastName"
type="text"
name="creationUsr.lastName"
id="creationUsr.lastName"
class="login-text"
placeholder="${lastNameMessage}"
value=""/>
Im trying to write a controller and a form that can handle a multipart file upload and some other data passing.
First i made the basic form like this:
<form:form method="POST" commandName="myForm">
then everything fine, but no multipart handling of course. Then i add the enctype part like this:
<form:form method="POST" commandName="myForm" enctype="multipart/form-data">
Then my whole form is messed up and all the attribuets gives NullPointers. Not even a simple String name attribute working. Also i added:
<beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
So i really got no idea whats the problem. Any comment would help a lot. Thnaks in advance.
We are using CommonsMultipartResolver in our project. It goes like this. In your applicationContext.xml:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- one of the properties available; the maximum file size in bytes -->
<property name="maxUploadSize" value="1048576000"/>
<property name="defaultEncoding" value="UTF-8" />
</bean>
Then cast yout request to MultipartHttpServletRequest:
public ModelAndView handleRequest(HttpServletRequest req, HttpServletResponse resp) throws Exception {
if (!(req instanceof MultipartHttpServletRequest)) {
error(resp, "Invalid request (multipart request expected)");
return null;
}
Map<String, MultipartFile> files = ((MultipartHttpServletRequest)req).getFileMap();
... do thomething with the files