복붙노트

[SPRING] 봄 MVC 파일 업로드 도움말

SPRING

봄 MVC 파일 업로드 도움말

나는 스프링을 응용 프로그램에 통합하여 양식에서 업로드 한 파일을 다시 실행해야합니다. Spring MVC가 제공해야하는 것과 컨트롤러를 구성하여 파일을 업로드 할 수 있어야하는 것에 대해 알고 있습니다. 나는 이것을 할 수있는 튜토리얼을 충분히 읽었지만,이 튜토리얼에서 설명하지 않은 것은 당신이 가지고있는 파일을 실제로 처리하기 위해 어떻게 / 해야할지에 대한 올바른 / 최선의 연습 방법이다. 아래는 Spring MVC 문서에서 발견 할 수있는 코드와 비슷한 코드입니다. 봄 MVC 파일 업로드

아래 예제에서 파일을 가져 오기 위해해야 ​​할 일을 모두 보여 주지만, 콩으로 뭔가를 수행한다고 말하면됩니다.

나는 많은 튜토리얼을 확인했고,이 모든 것들은이 시점까지 나에게 가져다 줄 것으로 보인다. 그러나 정말로 알고 싶은 것은 파일을 다루는 가장 좋은 방법이다. 이 시점에서 파일을 얻었 으면이 파일을 서버의 디렉토리에 저장하는 가장 좋은 방법은 무엇입니까? 누군가 이걸로 제발 도와 줄 수 있어요? 감사

public class FileUploadController extends SimpleFormController {

protected ModelAndView onSubmit(
    HttpServletRequest request,
    HttpServletResponse response,
    Object command,
    BindException errors) throws ServletException, IOException {

     // cast the bean
    FileUploadBean bean = (FileUploadBean) command;

     let's see if there's content there
    byte[] file = bean.getFile();
    if (file == null) {
         // hmm, that's strange, the user did not upload anything
    }

    //do something with the bean 
    return super.onSubmit(request, response, command, errors);
}

해결법

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

    1.이것은 내가 업로드하는 동안 선호하는 것입니다. 나는 봄이 파일 저장을 처리하도록하는 것이 가장 좋은 방법이라고 생각합니다. Spring은 MultipartFile.transferTo (File dest) 함수로 처리한다.

    이것은 내가 업로드하는 동안 선호하는 것입니다. 나는 봄이 파일 저장을 처리하도록하는 것이 가장 좋은 방법이라고 생각합니다. Spring은 MultipartFile.transferTo (File dest) 함수로 처리한다.

    import java.io.File;
    import java.io.IOException;
    
    import javax.servlet.http.HttpServletResponse;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.multipart.MultipartFile;
    
    @Controller
    @RequestMapping("/upload")
    public class UploadController {
    
        @ResponseBody
        @RequestMapping(value = "/save")
        public String handleUpload(
                @RequestParam(value = "file", required = false) MultipartFile multipartFile,
                HttpServletResponse httpServletResponse) {
    
            String orgName = multipartFile.getOriginalFilename();
    
            String filePath = "/my_uploads/" + orgName;
            File dest = new File(filePath);
            try {
                multipartFile.transferTo(dest);
            } catch (IllegalStateException e) {
                e.printStackTrace();
                return "File uploaded failed:" + orgName;
            } catch (IOException e) {
                e.printStackTrace();
                return "File uploaded failed:" + orgName;
            }
            return "File uploaded:" + orgName;
        }
    }
    
  2. ==============================

    2.가장 좋은 방법은 수행하려는 작업에 따라 다릅니다. 보통 나는 업로드 된 파일을 post-proccessing하기 위해 AOP를 사용한다. 그런 다음 FileCopyUtils를 사용하여 업로드 한 파일을 저장할 수 있습니다.

    가장 좋은 방법은 수행하려는 작업에 따라 다릅니다. 보통 나는 업로드 된 파일을 post-proccessing하기 위해 AOP를 사용한다. 그런 다음 FileCopyUtils를 사용하여 업로드 한 파일을 저장할 수 있습니다.

    @Autowired
    @Qualifier("commandRepository")
    private AbstractRepository<Command, Integer> commandRepository;
    
    protected ModelAndView onSubmit(...) throws ServletException, IOException {
        commandRepository.add(command);
    }
    

    AOP는 다음과 같이 설명됩니다.

    @Aspect
    public class UploadedFileAspect {
    
        @After("execution(* br.com.ar.CommandRepository*.add(..))")
        public void storeUploadedFile(JoinPoint joinPoint) {
            Command command = (Command) joinPoint.getArgs()[0];
    
            byte[] fileAsByte = command.getFile();
            if (fileAsByte != null) {
                try {
                    FileCopyUtils.copy(fileAsByte, new File("<SET_UP_TARGET_FILE_RIGHT_HERE>"));
                } catch (IOException e) {
                    /**
                      * log errors
                      */
                }
            }
    
        }
    

    애스펙트 사용 (반드시 스프링 3.0으로 스키마 업데이트 필요) 클래스 패스 aspectjrt.jar와 aspectjweaver.jar ( / lib / aspectj)와

    <beans xmlns="http://www.springframework.org/schema/beans"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xmlns:aop="http://www.springframework.org/schema/aop"
          xsi:schemaLocation="http://www.springframework.org/schema/beans
                              http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
                              http://www.springframework.org/schema/aop
                              http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
        <aop:aspectj-autoproxy />
        <bean class="br.com.ar.aop.UploadedFileAspect"/>
    
  3. ==============================

    3.아래의 컨트롤러 클래스를 사용하여 파일 업로드를 처리하십시오.

    아래의 컨트롤러 클래스를 사용하여 파일 업로드를 처리하십시오.

    @Controller
    public class FileUploadController {
    
      @Autowired
      private FileUploadService uploadService;
    
      @RequestMapping(value = "/fileUploader", method = RequestMethod.GET)
      public String home() {
        return "fileUploader";
      }
    
      @RequestMapping(value = "/upload", method = RequestMethod.POST)
      public @ResponseBody List<UploadedFile> upload(MultipartHttpServletRequest request, HttpServletResponse response) throws IOException {
    
        // Getting uploaded files from the request object
        Map<String, MultipartFile> fileMap = request.getFileMap();
    
        // Maintain a list to send back the files info. to the client side
        List<UploadedFile> uploadedFiles = new ArrayList<UploadedFile>();
    
        // Iterate through the map
        for (MultipartFile multipartFile : fileMap.values()) {
    
          // Save the file to local disk
          saveFileToLocalDisk(multipartFile);
    
          UploadedFile fileInfo = getUploadedFileInfo(multipartFile);
    
          // Save the file info to database
          fileInfo = saveFileToDatabase(fileInfo);
    
          // adding the file info to the list
          uploadedFiles.add(fileInfo);
        }
    
        return uploadedFiles;
      }
    
      @RequestMapping(value = {"/listFiles"})
      public String listBooks(Map<String, Object> map) {
    
        map.put("fileList", uploadService.listFiles());
    
        return "listFiles";
      }
    
      @RequestMapping(value = "/getdata/{fileId}", method = RequestMethod.GET)
      public void getFile(HttpServletResponse response, @PathVariable Long fileId) {
    
        UploadedFile dataFile = uploadService.getFile(fileId);
    
        File file = new File(dataFile.getLocation(), dataFile.getName());
    
        try {
          response.setContentType(dataFile.getType());
          response.setHeader("Content-disposition", "attachment; filename=\"" + dataFile.getName() + "\"");
    
          FileCopyUtils.copy(FileUtils.readFileToByteArray(file), response.getOutputStream());
    
    
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    
    
      private void saveFileToLocalDisk(MultipartFile multipartFile) throws IOException, FileNotFoundException {
    
        String outputFileName = getOutputFilename(multipartFile);
    
        FileCopyUtils.copy(multipartFile.getBytes(), new FileOutputStream(outputFileName));
      }
    
      private UploadedFile saveFileToDatabase(UploadedFile uploadedFile) {
        return uploadService.saveFile(uploadedFile);
      }
    
      private String getOutputFilename(MultipartFile multipartFile) {
        return getDestinationLocation() + multipartFile.getOriginalFilename();
      }
    
      private UploadedFile getUploadedFileInfo(MultipartFile multipartFile) throws IOException {
    
        UploadedFile fileInfo = new UploadedFile();
        fileInfo.setName(multipartFile.getOriginalFilename());
        fileInfo.setSize(multipartFile.getSize());
        fileInfo.setType(multipartFile.getContentType());
        fileInfo.setLocation(getDestinationLocation());
    
        return fileInfo;
      }
    
      private String getDestinationLocation() {
        return "Drive:/uploaded-files/";
      }
    }
    
  4. from https://stackoverflow.com/questions/3577942/spring-mvc-file-upload-help by cc-by-sa and MIT license