grails文件上传下载

//1.controller
package com.xdth

class UploadController {

    def index() {
        render(view:"../index")
    }

    /**
     * 文件上传
     * @return
     */
    def upload(){
        /*定义文件上传基本目录*/
        def path = "/upload"
        def basePath = request.getSession().getServletContext().getRealPath(path)

        //检查upload是否存在
        File saveFile = new File(basePath)
        if(!saveFile.exists()){
            saveFile.mkdirs()
        }

        def description = params["description"]
        def file = request.getFile("myFile")
        //上传文件原文件名
        def oldName = file.getOriginalFilename()

        if(file){
            //用时间戳作为新文件名
            def newName = System.currentTimeMillis()+oldName.substring(oldName.lastIndexOf(".",oldName.length()-1))

            //上传文件开始
            file.transferTo(new File(basePath+File.separator+newName))
            Upload upload = new Upload(oldName,newName,basePath,description)
            upload.save()
        }

        flash.message = "${oldName} 上传成功!"
        //从一个action跳转到另一个action
        redirect action:"show",model: [params:params]
    }

    /**
     * 文件下载
     * @return
     */
    def download(){
        def upload = Upload.findById(params.id)
        //File.separator根据当前系统自动获取盘符
        def downloadPath = upload.filePath+File.separator+upload.newName
        def file_name = upload.newName

        def bis = new BufferedInputStream(new FileInputStream(downloadPath))
        def bos = new BufferedOutputStream(response.outputStream)

        long fileLength = new File(downloadPath).length()

        response.setCharacterEncoding("UTF-8")
        response.setContentType("multipart/form-data")

        String userAgent = request.getHeader("User-Agent").toLowerCase()

        if (userAgent.contains("msie") || userAgent.contains("like gecko"))
        {
            // win10 ie edge 浏览器 和其他系统的ie
            file_name = URLEncoder.encode(file_name, "UTF-8")
        }
        else
        {
            file_name = new String(file_name.getBytes("UTF-8"), "iso-8859-1")
        }

        response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", file_name))
        response.setHeader("Content-Length", String.valueOf(fileLength))

        byte[] buff = new byte[2048]
        int bytesRead
        while (-1 != (bytesRead = bis.read(buff, 0, buff.length)))
        {
            bos.write(buff, 0, bytesRead)
        }
        bis.close()
        bos.close()
    }

    /**
     * 全部文件查看
     * @return
     */
    def show(){
        def max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        def offset = params.offset ? params.offset.toInteger() : 0

        def queryList = Upload.executeQuery("from Upload",[max:max,offset:offset]).asList()
        respond queryList,view: "show",model: [queryList:queryList,params:params,count:queryList.size()]
    }
}

2.index.gsp

<body>

    <div>
        <g:form controller="upload" action="upload" method="post" enctype="multipart/form-data">
        <table>
            <tr>
                <td><input type="file" name="myFile"></td>
                <td>文件描述:<textarea maxlength="50" name="description"></textarea></td>
            </tr>
            <tr>
                <td colspan="2"><button type="submit">上传文件</button></td>
            </tr>
        </table>
        </g:form>
    </div>

    <div>
        <g:link controller="upload" action="show">查看全部文件</g:link>
    </div>

</body>

3.show.gsp

    <body>
        <div class="nav" role="navigation">
            ${flash.message}
        </div>
    <div class="nav">
        <g:form action="show">
        <table>
            <tr>
                <g:sortableColumn property="id" action="show" title="id" params="${params}"/>
                <g:sortableColumn property="oldName" action="show" title="原文件名" params="${params}"/>
                <g:sortableColumn property="newName" action="show" title="现文件名" params="${params}"/>
                <g:sortableColumn property="description" action="show" title="文件描述" params="${params}"/>
                <td>操作</td>
            </tr>
            <g:each in="${queryList}" var="it">
                <tr>
                    <td>${it.id}</td>
                    <td>${it.oldName}</td>
                    <td>${it.newName}</td>
                    <td>${it.description}</td>
                    <td><g:link action="download" id="${it.id}">下载</g:link></td>
                </tr>
            </g:each>
        </table>
        </g:form>
    </div>
    <div class="panel-footer">
        <div class="pagination">
            <!--分页标签默认显示10条-->
            共${count?:0}条 &nbsp;&nbsp;
            <g:paginate total="${count?:0}" params="${params}"/>
        </div>
    </div>
    <br/>
    <g:link controller="upload" action="index">返回</g:link>
    </body>

猜你喜欢

转载自jun1986.iteye.com/blog/2406665