3

I have repository class where I want to store the image that is coming from MultipartFile to webapp/resources/images directory before adding the product details to the repository ?

@Override
public void addProduct(Product product) {
    Resource resource = resourceLoader.getResource("file:webapp/resources/images");

     MultipartFile proudctImage = product.getProudctImage();

     try {
        proudctImage.transferTo(new File(resource.getFile()+proudctImage.getOriginalFilename()));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    listOfProducts.add(product);
}

my repository class is ResourceLoaderAware. I am getting fileNotFoundException, "imagesDesert.jpg" is the image I am trying to upload

java.io.FileNotFoundException: webapp\resources\imagesDesert.jpg (The system cannot find the path specified)
2
  • Adding file to the classpath can make your container restart (I think about tomcat), that's not a good idea. What is the purpose of that (what problem are you trying to solve) Commented Nov 12, 2013 at 6:29
  • I have updated my code in the question, what I am trying is to upload an product image during adding a product and would like to show that image in the product details page Commented Nov 12, 2013 at 6:39

2 Answers 2

10

this controller (courtesy: https://askgif.com/) is working fine for me.

source: https://askgif.com/blog/126/how-can-i-upload-image-using-spring-mvc-java/

try this

package net.viralpatel.spring3.controller;


import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import net.viralpatel.spring3.form.FileUploadForm;

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


@Controller
 public class FileUploadController {

//private String saveDirectory = "D:/Test/Upload/"; //Here I Added
private String saveDirectory = null; //Here I Added

@RequestMapping(value = "/show", method = RequestMethod.GET)
public String displayForm() {
    return "file_upload_form";
}

@SuppressWarnings("null")
@RequestMapping(value = "/save", method = RequestMethod.POST)
public String save(
        @ModelAttribute("uploadForm") FileUploadForm uploadForm,
                Model map,HttpServletRequest request) throws IllegalStateException, IOException{

    List<MultipartFile> files = uploadForm.getFiles();
    List<String> fileUrl = new ArrayList<String>();;
    String fileName2 = null;
    fileName2 = request.getSession().getServletContext().getRealPath("/");


    saveDirectory = fileName2+"images\\";

    List<String> fileNames = new ArrayList<String>();

    //System.out.println("user directory : "+System.getProperty("user.dir"));
    System.out.println("applied directory : " + saveDirectory);
    if(null != files && files.size() > 0) {
        for (MultipartFile multipartFile : files) {

            String fileName = multipartFile.getOriginalFilename();
            System.out.println("applied directory : " + saveDirectory+fileName);
            if(!"".equalsIgnoreCase(fileName)){
                   //Handle file content - multipartFile.getInputStream()
                   fileUrl.add(new String(saveDirectory + fileName));

                   multipartFile.transferTo(new File(saveDirectory + fileName));   //Here I Added
                   fileNames.add(fileName);
                   }
            //fileNames.add(fileName);
            //Handle file content - multipartFile.getInputStream()
            //multipartFile.transferTo(new File(saveDirectory + multipartFile.getOriginalFilename()));   //Here I Added
        }
    }

    map.addAttribute("files", fileNames);
    map.addAttribute("imageurl",fileUrl);
    return "file_upload_success";
}
  }
Sign up to request clarification or add additional context in comments.

4 Comments

Hi Sumit, this is a good approach indeed, but I am in repository, I don't have access to HttpServletRequest, my repository already implements ResourceLoaderAware. So is there any way I can get request.getSession().getServletContext().getRealPath("/") through resource
finally I used your approach....instead of saving the image from repository I have saved in the controller itself
Hi Sumit, your answer is one kind of approach to the problem, but that is not the exact answer for the question. finally I found the answer my self, any how thanks a lot for your time and help
No problem, we are only assisting you here, it's not our job to complete your task. :)
4

Finally I could able to fix this problem, we need not specify the file: prefix, and moreover by default resourceLoader.getResource() will look for resources in the root directory of our web application, So no need of specifying the webapp folder name. So finally the following code works for me

@Override
public void addProduct(Product product) {

    MultipartFile proudctImage = product.getProudctImage();

    if (!proudctImage.isEmpty()) {
        try {
            proudctImage.transferTo(resourceLoader.getResource("resources/images/"+product.getProductId()+".png").getFile());

        } catch (Exception e) {
            throw new RuntimeException("Product Image saving failed", e);
        }
    }

    listOfProducts.add(product);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.