복붙노트

[SPRING] spring mvc를 사용하여 webapp / resources / images 디렉토리에 이미지를 업로드하는 방법은 무엇입니까?

SPRING

spring mvc를 사용하여 webapp / resources / images 디렉토리에 이미지를 업로드하는 방법은 무엇입니까?

저장소에 제품 세부 정보를 추가하기 전에 MultipartFile에서 오는 이미지를 webapp / resources / images 디렉토리에 저장하려는 저장소 클래스가 있습니까?

@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);
}

내 저장소 클래스는 ResourceLoaderAware입니다. fileNotFoundException이 발생합니다. "imagesDesert.jpg"는 업로드하려고하는 이미지입니다.

java.io.FileNotFoundException: webapp\resources\imagesDesert.jpg (The system cannot find the path specified)

해결법

  1. ==============================

    1.이 컨트롤러는 나를 위해 잘 작동합니다.

    이 컨트롤러는 나를 위해 잘 작동합니다.

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

    이 시도

    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";
    }
      }
    
  2. ==============================

    2.마지막으로이 문제를 해결할 수 있습니다. 접두사를 지정하지 않아도됩니다. 기본적으로 resourceLoader.getResource ()는 웹 응용 프로그램의 루트 디렉토리에서 리소스를 검색하므로 webapp 폴더 이름을 지정할 필요가 없습니다. 그래서 마침내 다음 코드가 작동합니다.

    마지막으로이 문제를 해결할 수 있습니다. 접두사를 지정하지 않아도됩니다. 기본적으로 resourceLoader.getResource ()는 웹 응용 프로그램의 루트 디렉토리에서 리소스를 검색하므로 webapp 폴더 이름을 지정할 필요가 없습니다. 그래서 마침내 다음 코드가 작동합니다.

    @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);
    }
    
  3. from https://stackoverflow.com/questions/19922358/how-to-upload-an-image-to-webapp-resources-images-directory-using-spring-mvc by cc-by-sa and MIT license