Using Multipart Resolver:
To work with images or files with spring you should use the multipart resorver. There are two multipart resolvers in the spring
- CommonsMultipartResolver: you need commons-fileupload.jar to work with this resolver.
- CosmultipartResolver : You need Cos.jar to work with resolver.
Apart from these jar files add the dependent jar files also into the application.
You can specify the maximum size of the image in the bits with the <property /> tag under the <bean > tag.
<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="100000"/>
</bean>
(or)
<bean id="multipartResolver" class="org.springframework.web.multipart .cos.CosMultipartResolver">
<!-- one of the properties available; the maximum file size in bytes -->
<property name="maxUploadSize" value="100000"/>
</bean>
uploadfile.jsp:
Create the jsp to upload the image. The form enctype should be 'multipart/form-data' and use the file tag to get the browse option in the page.
<html>
<head>
<title>Upload a file Example</title>
</head>
<body>
<h1>Browse a file</h1>
<form method="post" action="upload.form" name='uploadForm' enctype="multipart/form- data">
<input type="file" name="file"/>
<input type="submit"/>
</form>
</body>
</html>
Form Bean:
Write the Bean class for the fileUpload.jsp. You can specify the file data type as MultipartFile or byte or
public class FileUploadBean {
private MultipartFile file;
public void setFile(MultipartFile file) {
this.file = file;
}
public MultipartFile getFile() {
return file;
}
}
FileUploadController.java:
Read the image using the controller class.
public class FileUploadController extends SimpleFormController {
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws ServletException, IOException {
// cast the bean
FileUploadBean bean = (FileUploadBean) command;
MultipartFile file = bean.getFile();
if (file == null) {
System.out.println("Unable to rad the image from Jsp");
}
//While writing it into data base if you want to use in the byte array you can convert it
byte imageArray[] = file.getBytes();
//once you got the byte array you can save it in database get the database connection
//save it in the database
return super.onSubmit(request, response, command, errors);
}
}
Configuring in Dispatcher Servletxml:
<beans>
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<value>
/upload.form=fileUploadController
</value>
</property>
</bean>
<bean id="fileUploadController" lass="examples.FileUploadController">
<property name="commandClass" value="examples.FileUploadBean"/>
<property name="formView" value="fileuploadform"/>
<property name="successView" value="confirmation"/>
</bean>
</beans>
1 comment:
Post a Comment