如何在grails中获取文件

时间:2014-02-04 06:23:20

标签: grails

如何在Grails中获取文件? 我尝试了这段代码但是没有成功..

 def upload = {
        withForm{
            def f = request.getFile('filecsv')
            def orifilename = f.getOriginalFilename()
            def homeDir = new File(System.getProperty("user.home")) 
            def homeurl = "Documents/Uploads/"
            File fileDest = new File(homeDir,homeurl+orifilename)
            f.transferTo(fileDest)  

            def card = Card
            def cif = Cif

            request.getFile(new File(fileDest)).InputStream.splitEachLine(',') {fields ->
            def loanaccount = new LoanAccount(
                totalLoanAmount: fields[0].trim(),
                outstandingAmount: fields[1].trim(),
                installmentAmount: fields[2].trim(),
                collectionDate: fields[3].trim(),
                dueDate: fields[4].trim(),
                interestRate: fields[5].trim(),
                card:card.findAllByCardNo(field[6]).trim(),
                cif :cif.findAllByFirstName(field[7]).trim()
                )
            if (loanaccount.hasErrors() || loanaccount.save(flush: true) == null)
            {
                log.error("Could not import domainObject  ${loanaccount.errors}")
            }
            }

            redirect(action:"list")

        }
            }

为什么会出错?

但获取文件是错误的......

2014-02-04 15:38:50,648 [http-8080-11] ERROR errors.GrailsExceptionResolver  - Could not find matching constructor for: java.io.File(java.io.File)
groovy.lang.GroovyRuntimeException: Could not find matching constructor for: java.io.File(java.io.File)
        at com.teravin.wallet.LoanAccountController$_closure12_closure16.doCall(com.teravin.wallet.LoanAccountController:322)
        at com.teravin.wallet.LoanAccountController$_closure12_closure16.doCall(com.teravin.wallet.LoanAccountController)
        at com.teravin.wallet.LoanAccountController$_closure12.doCall(com.teravin.wallet.LoanAccountController:308)
        at com.teravin.wallet.LoanAccountController$_closure12.doCall(com.teravin.wallet.LoanAccountController)
        at java.lang.Thread.run(Thread.java:744)

我正在使用Grails 2.1.1。我试图在谷歌找到一些文档,但仍然无法解决我的问题。

1 个答案:

答案 0 :(得分:0)

问题出在这里

request.getFile(new File(fileDest)).InputStream.splitEachLine(',') {fields ->

您在此处不需要request.getFile,因为您已经处理了文件上传并将其转移到临时文件中,只需使用

fileDest.splitEachLine(',', 'UTF-8') { fields ->

请注意,您应该使用splitEachLine的显式编码,而不是依赖于默认的平台默认值。您可以检查浏览器发送的Content-Type以查看是否指定了字符集,然后返回默认值UTF-8(或其他),如果不是。

如果有问题的变量实际上被称为field[6]并且带有s,那么您还会在下一个拼写错误的地方向下引用field[7]fields