上传grails文件

时间:2012-09-15 16:30:20

标签: grails input

我正在尝试上传我的gsp中的grails文件:

<g:form id="update" url="[action: 'updateStatus',]">
     <g:textArea name="message" value="" cols="3" rows="1"/><br/>
     <g:textField id="tagField" name="tag" value=""/><br/>
     <input id="inputField" type="file" name="myFile" enctype="multipart/form-data" />
     <g:submitButton name="Update Status"/>
 </g:form>

在我的控制器中我有:

 def updateStatus(String message) {

        if (params.myFile){
            def f = request.getFile('myFile')

        }

请求获取文件失败并显示以下错误:

No signature of method: org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestWrapper.getFile() is applicable for argument types: (java.lang.String) values: [myFile]

任何想法为什么这就像我一样,并且在我的其他控制器中使用getFile工作正常。

3 个答案:

答案 0 :(得分:7)

这是工作文件提交:

表格(gsp)

<form method="post" enctype="multipart/form-data">
<p><input type='file' name="cfile"/></p>
<input type='submit'>
</form>

将提交的文件存储到'D:/ submitted_file'的控制器:

def index() {
    if(params.cfile){
        if(params.cfile instanceof org.springframework.web.multipart.commons.CommonsMultipartFile){
            new FileOutputStream('d:/submitted_file').leftShift( params.cfile.getInputStream() );
            //params.cfile.transferTo(new File('D:/submitted_file'));
        }else{
            log.error("wrong attachment type [${cfile.getClass()}]");
        }
    }
}

这对我有用(grails 2.0.4)

答案 1 :(得分:3)

enctype="multipart/form-data"标记上需要g:form才能使浏览器使用多部分请求。

答案 2 :(得分:0)

In order to upload a file you must set the enctype on the form. To do so you can make use of the <g:uploadForm> which is identical to the standard form tag except that it sets the enctype attribute to "multipart/form-data" automatically.

I prefer to make use of the Grails Selfie Plugin an Image / File Upload Plugin to attach files to your domain models, upload to a CDN, validate content, or produce thumbnails.

Domain

import com.bertramlabs.plugins.selfie.Attachment

class Book {
   String name
   Attachment photo

   static attachmentOptions = [
       photo: [
           styles: [
              thumb: [width: 50, height: 50, mode: 'fit'],
              medium: [width: 250, height: 250, mode: 'scale']
          ]
       ]
   ]

   static embedded = ['photo'] //required

   static constraints = {
      photo contentType: ['image/jpeg','image/png'], fileSize:1024*1024 // 1mb
   }
}

GSP

<g:uploadForm name="myUpload" controller="upload" action="updateStatus">
    <input type="file" name="myFile" />
</g:uploadForm>

Controller

class PhotoController {
   def upload() {
      def photo = new Photo(params)
      if(!photo.save()) {
         println "Error Saving! ${photo.errors.allErrors}"
      }
      redirect view: "index"
   }
}

Sources

1. uploadFrom

2. selfie plugin