Upload an image to Spring -mvc

0

I'm trying to upload an image with Spring-mvc utilziando for it Commons FileUpload I'm following the following link I call fileUpload on my controller and it enters but does not upload the image. The steps that I have followed are: Add the dependency:

<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
</dependency>

I have set the MultipartConfigElement by adding the location and maximum size to what I already had

public class SpringWebAppInitializer implements WebApplicationInitializer {

private String TMP_FOLDER = "C:/Users/SilviaGM/Desktop/git tfg"; 
private int MAX_UPLOAD_SIZE = 5 * 1024 * 1024; 



public void onStartup(ServletContext servletContext) throws ServletException {
            AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();
            appContext.register(ApplicationContextConfig.class);

            // Dispatcher Servlet
            ServletRegistration.Dynamic dispatcher = servletContext.addServlet("SpringDispatcher",
                    new DispatcherServlet(appContext));
            dispatcher.setLoadOnStartup(1);
            dispatcher.addMapping("/");

            dispatcher.setInitParameter("contextClass", appContext.getClass().getName());

            servletContext.addListener(new ContextLoaderListener(appContext));

            // UTF8 Charactor Filter.
            FilterRegistration.Dynamic fr = servletContext.addFilter("encodingFilter", CharacterEncodingFilter.class);

            fr.setInitParameter("encoding", "UTF-8");
            fr.setInitParameter("forceEncoding", "true");
            fr.addMappingForUrlPatterns(null, true, "/*");  


            //Nuevo para subir la imagen
            ServletRegistration.Dynamic appServlet = servletContext.addServlet("mvc", new DispatcherServlet(
                    new GenericWebApplicationContext()));

                  appServlet.setLoadOnStartup(1);

                  MultipartConfigElement multipartConfigElement = new MultipartConfigElement(TMP_FOLDER, 
                    MAX_UPLOAD_SIZE, MAX_UPLOAD_SIZE * 2, MAX_UPLOAD_SIZE / 2);

                  appServlet.setMultipartConfig(multipartConfigElement);
        }
    }

I added the @Bean

@Configuration
@EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    // Static Resource Config 
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/css/**").addResourceLocations("/css/").setCachePeriod(31556926);
        registry.addResourceHandler("/img/**").addResourceLocations("/img/").setCachePeriod(31556926);
        registry.addResourceHandler("/js/**").addResourceLocations("/js/").setCachePeriod(31556926);
    }


    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

    @Bean(name = "multipartResolver")
    public CommonsMultipartResolver multipartResolver() {
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
        multipartResolver.setMaxUploadSize(100000);
        return multipartResolver;
    }
}

And finally I added the method to the controller:

@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public String submit(@RequestParam("file") MultipartFile file, ModelMap modelMap) {
    modelMap.addAttribute("file", file);
     System.out.println("Estoy aqui"); //Me muestra el valor por lo que es llamado el metodo.
    return "fileUploadView";
}
  

My problem is that the image is not uploaded to the directory: "C: / Users / SilviaGM / Desktop / git tfg"; and I can not find the problem or if I'm missing something in the configuration

    
asked by Silvia 08.05.2018 в 21:00
source

1 answer

0

Hello regarding the configuration part:

MultipartConfigElement multipartConfigElement = new MultipartConfigElement(TMP_FOLDER, MAX_UPLOAD_SIZE, MAX_UPLOAD_SIZE * 2, MAX_UPLOAD_SIZE / 2);

The last parameter indicates when the files will be automatically persisted in the indicated location, therefore you have several situations among these that your file is not reaching the minimum size to be automatically persisted

Of pretending to do the process manually, what you have left would be to validate that it is not empty and finally to persist it in the way you prefer it, be it on the hard disk, in a db etc ...

For this case I am going to do it in the hard disk since I see that it is what you are looking for, and I will use a library that will facilitate the process to me but you can do it with any other method. The library that I will use is called: org.apache.commons.io

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>

Now on your controller:

@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public String submit(@RequestParam("file") MultipartFile multipartFile, ModelMap 
modelMap) {
    //donde guardarás tu archivo, asegurate de que tengas permisos de escritura
    String pathFinal = "C:/archivosSubidos";
    //validación básica
    if(!multipartFile.isEmpty()){
      //creo un nuevo archivo
      File file = new File(pathFinal);
      FileUtils.touch(file);
      //transfiero el archivo multipart al disco.
      multipartFile.transferTo(file);
    }
    return "fileUploadView";
}

I have not yet been able to test my code, but as you realize, you must decide what to do with the file.

Greetings.

    
answered by 09.05.2018 / 18:53
source