uploading a file in grails

后端 未结 3 381
温柔的废话
温柔的废话 2021-01-02 09:17

I am trying to upload a file in grails in my gsp I have:


     

        
相关标签:
3条回答
  • 2021-01-02 09:54

    here is working file submit:

    the form (gsp)

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

    the controller that will store submitted file into '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()}]");
            }
        }
    }
    

    this works for me (grails 2.0.4)

    0 讨论(0)
  • 2021-01-02 10:09

    You need enctype="multipart/form-data" on the g:form tag to make the browser use a multipart request.

    0 讨论(0)
  • 2021-01-02 10:15

    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

    0 讨论(0)
提交回复
热议问题