Grails文件上传

Grails文件上传
在grails中实现上传文件也很简单。它可以使用spring里面的CommonsMultipartFile类来处理上传文件.
可以对文件的一些属性设置,比如大小:
<bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize">
<value>1000000</value>
</property>
</bean>
当然gsp页面需要在form里面设置enctype= "multipart/form-data"
<g:form method="post" action="save" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="submit"/>
</g:form>

下面就是处理上传的文件了:

import org.springframework.web.multipart.MultipartHttpServletRequest
import org.springframework.web.multipart.commons.CommonsMultipartFile

class UploadController {
    static String uploadDir = "uploadfile"
    def index = {
        render(view:"upload")
    }
    def save = {
        if (request instanceof MultipartHttpServletRequest) {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request
            CommonsMultipartFile orginalFile = (CommonsMultipartFile) multiRequest.getFile("file")
            // 判断是否上传文件
            if (orginalFile != null && !orginalFile.isEmpty()) {
                // 获取系统默认文件路径分隔符
                def separator = System.getProperty("file.separator")
                println "file separator is ${separator} "
                // 获取原文件名称
                String originalFilename = orginalFile.getOriginalFilename()
                // 获取上传文件扩展名
                def extension = originalFilename.substring(originalFilename.indexOf(".") + 1)
                println "extension is ${extension}"
                def name = ".." + separator + uploadDir + separator + orginalFile.getOriginalFilename()
                println "file name is : ${name}"
                // 使用存放文件的绝对路径创建输出流
                 /**
                DataOutputStream out = new DataOutputStream(new FileOutputStream(name))
                InputStream is = null
                try {
                    is = orginalFile.getInputStream()
                    byte[] buffer = new byte[1024]
                    while (is.read(buffer) > 0) {
                      out.write(buffer) // 写入磁盘
                    }
                } catch (IOException exception) {
                    exception.printStackTrace()
                } finally {
                    if (is != null) {
                        is.close()
                    }
                    if (out != null) {
                        out.close()
                    }
                }
                */
                orginalFile.transferTo(new File(name))
                render(view:"success")
            }
          
        } else {
            println "No multipart"
        }
    }
}


你可能感兴趣的:(Grails文件上传)