Time needed to complete ~20 minutes
1.Introduction
This article will show how to submit form that has file(s) to upload and write them to file system using spring framework.
2.What is used in this tutorial:
1- Maven 3
2- Jdk 1.7
3- Tomcat 7.0.55
4- Eclipse Luna 4.4
5- Spring Core 3.2.9
3.Project Structure
4. Form and controller
- CarUploadForm bean contains four fields, listing 4.1.
- CarAdController, Listing 4.2, the displayForm method will show the form in the get request and when the form is submitted saveForm method will handle the form data, save files to path in the file system. DIRECTORY_PATH is where the files will be written, this example used windows network path \\PC-phoenix\car_images , change is to suite your path (car_images is a shared directory) the controller then return success page.
5. View
- Form is in page carAdForm.jsp, Listing 5.1.6. Configuration
- In resources/spring/application-config.xml is the multipartResolver bean where the maximum size of each uploaded file can specified, Listing 6.1. Each uploaded file is limited to 1MB (1024000) using property maxUploadedSize.
- configure tomcat to be able to access \\PC-phoenix\car_images by adding file cars.xml to
path to tomcat diretory/conf/Catalina/localhost, cars.xml has one line, Listing 6.2.
7. Deploying to tomcat
Note: don't forget to change username and password for tomcat server in pom.xml file
- Start tomcat.
- Start tomcat.
- Deploy application from run configuration in goal type clean install tomcat7:redeploy
click Apply and Run buttons.
- In browser type http://localhost:8080/fu1/carAd/show to see the form picture 7.1.click Apply and Run buttons.
- Enter some data in text field, select some files and Submit. Picture 7.2. There is a server side validation for Manufacturer,model and note fields, if any of them is not entered error message will be shown.
- After submitting the data entered in the carAdForm will be displayed in success page, picture 7.3.
No comments:
Post a Comment