如何在GRAILS控制器中验证服务器端的任何文件上载?

时间:2015-09-25 05:12:10

标签: grails groovy

我的代码在gsp:

<html>
  <body>
    <g:form controller="some_controller" action="some_action" enctype="multipart/form-data">
       <input id="Resume" type="file" name="Resume" />
    </g:form>
  </body>
</html>

我的控制器代码:

def candidate = new Candidate(params)
MultipartHttpServletRequest mhsr = (MultipartHttpServletRequest) request
MultipartFile candResume = mhsr.getFile('candResume')

if(userService.fileExt().contains(candResume.getContentType()))
 {
 candidate.candResume=candResume.getBytes() //Converting a file into bytes
 if(candidate.validate())
   {
   if(candidate.save(flush: true,failOnError: true))
    {
     println "++++++++++Candidate Success+++++++++++++"
     flash.candSuccess="Candidate successfully added."
    }
   }
   else{
     println "====Sorry Candidate Upload Failed===="
     flash.candFail="Candidate failure."
   }
}

我的服务代码:

public List fileExt(){
        List fileExtensions=["doc", "docx", "pdf", "rtf"]
        println "--------in the service----------"
        return fileExtensions
    }

事情在 if(userService.fileExt()。contains(candResume.getContentType())) 该服务正在被调用,但没有在没有任何消息的情况下重新启动上传失败的任何内容。请帮忙。 提前谢谢。

2 个答案:

答案 0 :(得分:0)

我可能会这样做:

在控制器中:

def userService
def candidate = new Candidate(params)
  def resumeFile = request.getFile('candResume')

  if (userService.allowedExtension(resumeFile)) {
    blablabla

在服务中:

Class UserService {

  def allowedExtension (aFile) {
    List fileExtensions=["doc", "docx", "pdf", "rtf"]
    println "--------in the service----------"
    def extension = aFile?.originalFilename?.substring(aFile?.originalFilename?.lastIndexOf(".") + 1);
    return fileExtensions.contains(extension); // if you rely on the actual file name
  }
}

答案 1 :(得分:0)

我建议您使用mimetype而不是扩展文件。

在这里,您可以找到如何使用Tika获取文件的mimetype:Getting MimeType subtype with Apache tika