grails file upload and download

//1.controller
package com.xdth

class UploadController {

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

    /**
     * File Upload
     * @return
     */
    def upload(){
        /*Define file upload base directory*/
        def path = "/upload"
        def basePath = request.getSession().getServletContext().getRealPath(path)

        //check if upload exists
        File saveFile = new File(basePath)
        if(!saveFile.exists()){
            saveFile.mkdirs()
        }

        def description = params["description"]
        def file = request.getFile("myFile")
        //Upload original file name
        def oldName = file.getOriginalFilename()

        if(file){
            // use the timestamp as the new filename
            def newName = System.currentTimeMillis()+oldName.substring(oldName.lastIndexOf(".",oldName.length()-1))

            // start uploading file
            file.transferTo(new File(basePath+File.separator+newName))
            Upload upload = new Upload(oldName,newName,basePath,description)
            upload.save()
        }

        flash.message = "${oldName} uploaded successfully!"
        // jump from one action to another
        redirect action:"show",model: [params:params]
    }

    /**
     * document dowload
     * @return
     */
    def download(){
        def upload = Upload.findById(params.id)
        //File.separator automatically obtains the drive letter according to the current system
        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 browser and ie of other systems
            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()
    }

    /**
     * View all files
     * @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">View all files</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">
            <!--Pagination labels display 10 by default-->
            共${count?:0}条   
            <g:paginate total="${count?:0}" params="${params}"/>
        </div>
    </div>
    <br/>
    <g:link controller="upload" action="index">返回</g:link>
    </body>

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326392747&siteId=291194637