Retrieve the file name while using file type input

前端 未结 5 1607
南旧
南旧 2021-02-19 19:58

I have a jsp with this code snippet in it.

Choose Fil
5条回答
  •  庸人自扰
    2021-02-19 20:31

    When you upload the file, request is instance of org.springframework.web.multipart.MultipartHttpServletRequest. So you can cast it in your method convertFile(). See below :

    public String convertFile(HttpServletRequest request, HttpSession session) {
        // cast request
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        // You can get your file from request
        CommonsMultipartFile multipartFile =  null; // multipart file class depends on which class you use assuming you are using org.springframework.web.multipart.commons.CommonsMultipartFile
    
        Iterator iterator = multipartRequest.getFileNames();
    
        while (iterator.hasNext()) {
            String key = (String) iterator.next();
            // create multipartFile array if you upload multiple files
            multipartFile = (CommonsMultipartFile) multipartRequest.getFile(key);
        }
    
        // logic for conversion
    }
    

    However I am unable to retrieve (receiving null value) the name of the file that I chose in the JSP page.

    ---> To get file name you can get it as :

    multipartFile.getOriginalFilename();  // get filename on client's machine
    multipartFile.getContentType();       // get content type, you can recognize which kind of file is, pdf or image or doc etc
    multipartFile.getSize()          // get file size in bytes
    

    To make file upload work, you need to make sure you are creating multipart resolver bean as below :

    
    
        
        
    
    

    Reference : Spring documentation

提交回复
热议问题