groovy上传文件

时间:2012-03-17 21:31:29

标签: grails groovy

我正在尝试用grails / groovy编写文件和视频的上传器。 因此,每次用户填写新表单时,控制器都会上传文件并将文件名和其他字段一起保存到数据库中。所以,这是保存程序:

def save = {
        def streamInstance = new Stream(params)
        if(request){
            MultipartHttpServletRequest mpr = (MultipartHttpServletRequest)request;
            CommonsMultipartFile uploadedFile = (CommonsMultipartFile)mpr.getFile("myFile");
            if(!uploadedFile.empty){
                println "helloworld"
                println "Class: ${uploadedFile.class}"
                println "Name: ${uploadedFile.name}"
                println "OriginalFileName: ${uploadedFile.originalFilename}"
                println "Size: ${uploadedFile.size}"
                println "ContentType: ${uploadedFile.contentType}"
                /*
                //def webRootDir = servletContext.getRealPath("/")
                //def userDir = new File(webRootDir, "/files/${session.user.login}")
                //userDir.mkdirs()
                uploadedFile.transferTo(new File("/Users/philipperibeiro/ctv/ctv/web-app/files"))
                streamInstance.file = uploadedFile.originalFilename
                */
            }
            else{
                flash.message = "file cannot be empty"
            }
        }
        if(!streamInstance.hasErrors() && streamInstance.save(flush : true)){
            flash.message = "${message(code: 'default.created.message', args : [message(code: 'stream.label', default:'Stream'), streamInstance.id])}"
            redirect(action : "show", id : streamInstance.id)
        }
        else{
            render(view : "create", model : [streamInstance : streamInstance])
        }
    }

我收到此错误: 错误500:执行控制器[ctv.StreamController]的动作[save]导致异常:无法将类'org.apache.catalina.core.ApplicationHttpRequest'转换为对象'org.apache.catalina.core.ApplicationHttpRequest@19f46c5d'到类' org.springframework.web.multipart.MultipartHttpServletRequest” Servlet:Grails URI:/ctv/grails/stream/save.dispatch 异常消息:无法使用类'org.apache.catalina.core.ApplicationHttpRequest'将对象'org.apache.catalina.core.ApplicationHttpRequest@19f46c5d'转换为类'org.springframework.web.multipart.MultipartHttpServletRequest' 引发者:无法将对象'org.apache.catalina.core.ApplicationHttpRequest@19f46c5d'与类'org.apache.catalina.core.ApplicationHttpRequest'一起投射到类'org.springframework.web.multipart.MultipartHttpServletRequest' 类:StreamController 在线:[22] 代码段:

有人可以提供一个解决方法吗?

<%@ page import="ctv.Stream" %>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <meta name="layout" content="main" />
        <g:set var="entityName" value="${message(code: 'stream.label', default: 'Stream')}" />
        <title><g:message code="default.create.label" args="[entityName]" /></title>
        <jqfu:resources tmpl=”false” />
    </head>
    <body>
        <div class="nav">
            <span class="menuButton"><a class="home" href="${createLink(uri: '/')}"><g:message code="default.home.label"/></a></span>
            <span class="menuButton"><g:link class="list" action="list"><g:message code="default.list.label" args="[entityName]" /></g:link></span>
        </div>
        <div class="body">
            <h1><g:message code="default.create.label" args="[entityName]" /></h1>
            <g:if test="${flash.message}">
            <div class="message">${flash.message}</div>
            </g:if>
            <g:hasErrors bean="${streamInstance}">
            <div class="errors">
                <g:renderErrors bean="${streamInstance}" as="list" />
            </div>
            </g:hasErrors>
            <g:form action="save" >
                <div class="dialog">
                    <table>
                        <tbody>

                            <tr class="prop">
                                <td valign="top" class="name">
                                    <label for="district"><g:message code="stream.district.label" default="District" /></label>
                                </td>
                                <td valign="top" class="value ${hasErrors(bean: streamInstance, field: 'district', 'errors')}">
                                    <g:select name="district.id" from="${ctv.District.list()}" optionKey="id" value="${streamInstance?.district?.id}"  />
                                </td>
                            </tr>

                            <tr class="prop">
                                <td valign="top" class="name">
                                    <label for="dateAdded"><g:message code="stream.dateAdded.label" default="Date Added" /></label>
                                </td>
                                <td valign="top" class="value ${hasErrors(bean: streamInstance, field: 'dateAdded', 'errors')}">
                                    <g:datePicker name="dateAdded" precision="day" value="${streamInstance?.dateAdded}"  />
                                </td>
                            </tr>

                            <tr class="prop">
                                <td valign="top" class="name">
                                    <label for="name"><g:message code="stream.name.label" default="Name" /></label>
                                </td>
                                <td valign="top" class="value ${hasErrors(bean: streamInstance, field: 'name', 'errors')}">
                                    <g:textField name="name" maxlength="30" value="${streamInstance?.name}" />
                                </td>
                            </tr>

                            <tr class="prop">
                                <td valign="top" class="name">
                                    <label for="description"><g:message code="stream.description.label" default="Description" /></label>
                                </td>
                                <td valign="top" class="value ${hasErrors(bean: streamInstance, field: 'description', 'errors')}">
                                    <g:textField name="description" maxlength="100" value="${streamInstance?.description}" />
                                </td>
                            </tr>

                            <tr class="prop">
                                <td valign="top" class="name">
                                    <label for="media"><g:message code="stream.media.label" default="Media" /></label>
                                </td>
                                <td valign="top" class="value ${hasErrors(bean: streamInstance, field: 'media', 'errors')}">
                                    <g:textField name="media" maxlength="30" value="${streamInstance?.media}" />
                                </td>
                            </tr>

                            <tr class="prop">
                                <td valign="top" class="name">
                                    <label for="file"><g:message code="stream.file.label" default="File" /></label>
                                </td>
                                <td valign="top" class="value ${hasErrors(bean: streamInstance, field: 'file', 'errors')}">
                                    <!--g:textField name="file" maxlength="30" value="${streamInstance?.file}" />-->
                                    <g:form action="save"  enctype="multipart/form-data">
                                        <input type="file" name="myFile" />
                                    </g:form>
                                </td>
                            </tr>

                            <tr class="prop">
                                <td valign="top" class="name">
                                    <label for="logo"><g:message code="stream.logo.label" default="Logo" /></label>
                                </td>
                                <td valign="top" class="value ${hasErrors(bean: streamInstance, field: 'logo', 'errors')}">
                                    <g:textField name="logo" value="${streamInstance?.logo}" />
                                </td>
                            </tr>

                            <tr class="prop">
                                <td valign="top" class="name">
                                    <label for="published"><g:message code="stream.published.label" default="Published" /></label>
                                </td>
                                <td valign="top" class="value ${hasErrors(bean: streamInstance, field: 'published', 'errors')}">
                                    <g:checkBox name="published" value="${streamInstance?.published}" />
                                </td>
                            </tr>

                        </tbody>
                    </table>
                </div>
                <div class="buttons">
                    <span class="button"><g:submitButton name="create" class="save" value="${message(code: 'default.button.create.label', default: 'Create')}" /></span>
                </div>
            </g:form>
        </div>
    </body>
</html>

4 个答案:

答案 0 :(得分:7)

错误消息的原因

您的代码的问题在于您将请求对象强制转换为错误的类。这是错误消息的一部分,告诉您:

  

无法使用类'org.apache.catalina.core.ApplicationHttpRequest'将对象'org.apache.catalina.core.ApplicationHttpRequest@19f46c5d'强制转换为类'org.springframework.web.multipart.MultipartHttpServletRequest'

所以你有一个org.apache.catalina.core.ApplicationHttpRequest并且你正试图将它转换为无法完成的org.springframework.web.multipart.MultipartHttpServletRequest

groovy(写入grails)的美妙之处在于它是动态类型的。因此,无论如何,大部分演员都是多余的!

尝试替换这两行

MultipartHttpServletRequest mpr = (MultipartHttpServletRequest)request;
CommonsMultipartFile uploadedFile = (CommonsMultipartFile)mpr.getFile("myFile");

有了这个:

def uploadedFile = request.getFile( "myFile" )

但这不会解决你的问题!它只会更改您收到的错误消息:'(

问题的根源,以及我们如何以错误的请求类结束?

考虑到为什么您的演员阵容有错误的请求类型,您可能忘记在表单操作中包含enctype="multipart/form-data"。它应该看起来像这样:

<g:form action="save" method="post" enctype="multipart/form-data"> ... </g:form>

只是改变这个可能会解决你的问题,但我肯定会删除这个。

更新:真实(?)回答

在HTML(和GSP用于制作HTML)中,您不能拥有嵌套表单。一种形式不能在另一种形式中。您的GSP有两种形式,第一种形式如下:

<g:form action="save">

第二个(内部的)看起来像这样

<g:form action="save" enctype="multipart/form-data">

所以你需要彻底摆脱内部的一个,并确保外面的(唯一剩下的)看起来像这样:

<g:form action="save" method="post" enctype="multipart/form-data">

答案 1 :(得分:1)

我认为你可能会因此而复杂化。我们所做的只是

def image = request.getFile('image') // image is the parameter name 
def imageBytes = image.getBytes()

您还需要检查mimeType。

答案 2 :(得分:0)

另一种可以使用Grails文件上传插件的方法。请在此处查看更多信息http://grails.org/plugin/file-uploader。它具有强大的界面,并提供丰富的功能,使您的应用程序非常好用。

答案 3 :(得分:0)

您正在获得例外

groovy.lang.MissingMethodException:  No signature of method: 
  org.apache.catalina.core.ApplicationHttpRequest.getFile()

因为您尚未添加enctype

表单应该看起来像

<form action="action_name" method="POST" enctype="multipart/form-data">