Skip to content

Instantly share code, notes, and snippets.

@iamvickyav
Last active July 26, 2017 19:10
Show Gist options
  • Save iamvickyav/405f20563a863f122332bdbad9edcdbe to your computer and use it in GitHub Desktop.
Save iamvickyav/405f20563a863f122332bdbad9edcdbe to your computer and use it in GitHub Desktop.
Important things in File Upload in Spring MVC
Different & important pieces of codes for File Upload in Spring MVC
/** Form Coding in JSP **/
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" /> <input type="submit" value="submit" />
</form>
/** Code to handle file upload **/
@RequestMapping(value="/upload")
public ModelAndView upload(@RequestParam("file") MultipartFile file,
RedirectAttributes redirectAttributes) throws IOException{
System.out.println(file.getOriginalFilename());\
return new ModelAndView("uploadSuccess");
}
/** pom.xml **/
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3</version>
</dependency>
/** MvcConfiguration if Config done using annotation**/
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration
@ComponentScan(basePackages="com.digitalnative.attempts.SpringMVC")
@EnableWebMvc
public class MvcConfiguration extends WebMvcConfigurerAdapter{
@Bean
public ViewResolver getViewResolver(){
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
@Bean
public CommonsMultipartResolver multipartResolver() {
CommonsMultipartResolver resolver=new CommonsMultipartResolver();
resolver.setDefaultEncoding("utf-8");
return resolver;
}
}
/** If config is XML based **/
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
/** JSTL required **/
/** pom.xml **/
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
/** In JSP file **/
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment