Grails file upload - how to recognize file and/or content type?

后端 未结 3 1777
执笔经年
执笔经年 2021-02-08 16:05

I\'m a Grails beginner, so please be patient with me. Currently I\'m having hard times manipulating file uploads. As far as I understand using request.getFile() I c

相关标签:
3条回答
  • 2021-02-08 16:38

    From server side it is possible to use the configuration at application.yml to limit file size application wide.

    Just insert this code on your application.yml:

    grails:
      controllers:
        upload:
          maxFileSize: 3145728 # 3 * 1024 * 1024 = 3 MB The maximum file size
          maxRequestSize: 3145728 # The maximum request size
    

    See:

    Grails Guide - upload file

    Grails3 file upload maxFileSize limit

    0 讨论(0)
  • 2021-02-08 16:47

    Or you can get uploaded file properties directly without using CommonsMultipartFile.

    def ufile = request.getFile("fileInputName")
    println(ufile.contentType)
    println(ufile.originalFilename)
    println(ufile.size)

    0 讨论(0)
  • 2021-02-08 16:55

    All the information is contained in the CommonsMultipartFile object that you can cast your request parameter to.

    You can use it like that (in your controller)

    def uploaded = {
        def CommonsMultipartFile uploadedFile = params.fileInputName
        def contentType = uploadedFile.contentType 
        def fileName = uploadedFile.originalFilename
        def size = uploadedFile.size
    }
    

    As far as blocking large file uploads, this could be done by adding the following to your form:

    <INPUT name="fileInputName" type="file" maxlength="100000">
    

    but not all browsers will support it. The other limit is you container upload limit (see Tomcat configuration or whatever container you are using).

    Other than that, you have to check the size and reject it in the controller.

    0 讨论(0)
提交回复
热议问题