Skip to main content

Spring MVC - File upload Example


 spring-dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc   
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <mvc:annotation-driven />
    <context:component-scan base-package="myproject" />

    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".jsp" />
    </bean>


    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="100000" />
    </bean>

</beans>
Controller that handle file uploading
package myproject.controller;

import java.io.File;
import java.io.IOException;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;



@Controller
public class MyController {
    @RequestMapping(value={"/"})
    public String home(){
        return "Home";
    }
    @RequestMapping(value="/upload", method = RequestMethod.POST)
    public String upload(@RequestParam("file") MultipartFile file,Model model) throws IOException{
        if (!file.isEmpty()) {
            byte[] bytes = file.getBytes();//here you can write bytes to any file
            model.addAttribute("ContentType", file.getContentType());
            model.addAttribute("name", file.getName());
            model.addAttribute("OriginalName", file.getOriginalFilename());
            model.addAttribute("size", file.getSize());
   
            file.transferTo(new File("F:/temp/"+file.getOriginalFilename()));
  
            return "FileUploaded";
        }else {
            return "Home";
        }
    }
}

Form from where we upload the file
<html>
<head>
<title>Spring MVC - File Uploading Example</title>
</head>
<body>
    <h1>Spring MVC - File Uploading Example</h1>
    <form method="post" action="upload" enctype="multipart/form-data">
        <input type="file" name="file" />
        <input type="submit" />
    </form>
</body>
</html>
Result page 
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
     <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>File Uploaded</h1>
<h2>Name: ${name}</h2>
<h2>OriginalName: ${OriginalName}</h2>
<h2>ContentType: ${ContentType}</h2>
<h2>Size: ${size} bytes</h2>
</body>
</html>
List of Jar files 

Comments

Popular posts from this blog

Using HyperSQL (HSQLDB)

HSQLDB is a portable RDBMS implemented in pure java. It can be embedded with your application as well as can be used separately. It is very a small database that supports almost all features of the standard database system. It comes with small jar file that can be found in lib folder. The HSQLDB jar package is located in the /lib directory of the ZIP package and contains several components and programs. Core components of jar file are : HyperSQL RDBMS Engine (HSQLDB), HyperSQL JDBC Driver, Database Manager, and Sql Tool. Installing and Using Download: download latest release of HyperSQL database from http://hsqldb.org website and extract it. You will see following contents. Here "bin" directory contains some batch files those can be used to run a swing based GUI tool. You can use runManagerSwing.bat to connect to database, but database must be on before running it. Directory lib contains File hsqldb.jar . It is the database to be used by you. Running database First

How to handle values from dynamically generated elements in web page using struts2

Some time you will see the form containing the button " Add More " . This facility is provided for the user to get the values for unknown number of repeating for some information. for example when you are asking to get the projects details from user, you need to put the option to add the more project for the user since you don't known how many projects user have. In the HTML form, you repeat the particular section to get the multiple values for those elements. In Html page , you can put the option to add new row of elements or text fields by writing the java script or using JQuery API. Now, the question is that how to capture the values of dynamically generated text fields on the server. Using the servlet programming you can get the values by using getParameters() method that resultants the array of the parameter having the same name. But this limit you to naming the text fields in the HTML form. To ally this approach, you have to take the same name for t

Generating JTable from database table

package  process; import  javax.swing. * ; import  javax.swing.table. * ; import  java.sql. * ; /**  * This class create JTable from Database table.  * User program needs to specify database connection and corresponding atable name.  * @author Hemraj  */ public   class  TableToJTable {      //private String table;      private   Connection  con;      public   TableToJTable ( Connection  con ){          this .con = con;      }      /**      * This method return JTable object created from Database table having same data asn structure      * as in original table into database.      * @param table Name of the database table to be coverted to JTable      * @return JTable object that consist of data and structure of Database table      * @throws java.lang.Exception Original object is deferent, e.i either SQLException or NullPointerException      */      public   JTable   getTable ( String  table ) throws   Exception {          JTable  t1 = new   JTable () ;          D