简体   繁体   中英

Spring HTTP File Upload: Validation of File Size

I've a basic question about validation of file size in a Spring based HTTP File Upload Service. I am using Spring's org.springframework.web.multipart.MultipartFile to perform the file upload.

My question is does multipartFile.getSize() method return size only after completion of entire upload? If yes, what's the right look ahead approach to restrict files based on size?

Note: The reason I ask this question is because I do not want an end user to upload 1 GB file and get an error message after an hour saying, "Sorry, maximum file size allowed is 2 KB."

MultipartFile only check the file size in server side. if you want to check the file size at the time of upload you need to use client side javascript or jquery . javascript or jquery can be use to check the file side at the time of upload.

$('#myFile').bind('change', function() {

  //this.files[0].size gets the size of your file.
  alert(this.files[0].size);

});

I think the person do with it should be the front end programmer (javascript/h5) who should check the size before user uploading. Then the server side operator need to set some properties like "maxRequestLength" or "upload_max_filesize" for http request.

Answer to your first question,is does multipartFile.getSize() method return size only after completion of entire upload?

-No,you get multipartFile.getSize() before completion of entire upload.

@RequestMapping(value = "/CSVfileupload")
public @ResponseBody String callCSVFileUpload(
    @RequestParam("CSVfilepath") MultipartFile multipartFile, HttpSession session,HttpServletRequest request) throws IOException {
     //get the file size before doing any operation 
     logger.info("Controller - callCSVFileUpload() multipartFile.getSize()="+ multipartFile.getSize());
     InputStream inputStream =  new BufferedInputStream(multipartFile.getInputStream());
     JsonArray response=null;
     try{
         //you business logic 
        }
     catch(Exception e){
        e.printStackTrace();
        }
        logger.info(" response.toString()="+ response.toString());
        return response.toString();
    }//end of callCSVFileUpload

You can use CommonsMultipartResolver in you application-context.xml file.

<bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="50000000" />
</bean>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM