grails - 如何在GRAILS Controller 中验证服务器端上载的任何文件?

标签 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>

我的 Controller 代码:
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
    }

如果(userService.fileExt()。contains(candResume.getContentType())),那么它就在
服务被调用,但没有停止任何上载失败而没有任何消息的操作。请帮忙。
提前致谢。

最佳答案

我可能会做这样的事情:

在 Controller 中:

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
  }
}

关于grails - 如何在GRAILS Controller 中验证服务器端上载的任何文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32775235/

相关文章:

gradle - gradle避免依赖任务在异常发生时不运行

grails - 如何在Grails中发送电子邮件

java - Camel + Groovy + Spring DSL 的奇怪行为

grails - 覆盖Setter&Getter Domain类

grails - 如何从 GSP 中的常规辅助方法设置变量?

tomcat - 如何确保 Tomcat6 在 Windows 上读取 CATALINA_OPTS?

performance - Grails中的交易价格如何?

javascript - jQuery绑定(bind)点击不添加元素

sql-server - Grails SQLServerException Microsoft数据库 'limit'附近的语法不正确

grails - 无法解决依赖关系(Grails/Spring)