欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

grails文件下载+图片查看

程序员文章站 2022-07-05 09:56:34
...
/**
 * 下载
 * @return
*/
def download(){
    def fileObj = ValuationHistoryForNSQ.get(params["id"])
    def file_name = fileObj.getFile_name()
    def file_type = fileObj.getFile_type()
    def root_path = fileObj.getRoot_path()
    def file_path = fileObj.getFile_path()
    def downloadPath = root_path+file_path+file_name

    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 look(){
    def fileObj = ValuationHistoryForNSQ.get(params["id"])
    def file_name = fileObj.getFile_name()
    def file_type = fileObj.getFile_type()
    def root_path = fileObj.getRoot_path()
    def file_path = fileObj.getFile_path()
    def downloadPath = root_path+file_path+file_name

    //读取本地图片输入流
FileInputStream inputStream = new FileInputStream(downloadPath);
    int i = inputStream.available();
    //byte数组用于存放图片字节数据
byte[] buff = new byte[i];
    inputStream.read(buff);
    //记得关闭输入流
inputStream.close();
    //设置发送到客户端的响应内容类型
response.setContentType("image/*");
    OutputStream out = response.getOutputStream();
    out.write(buff);
    //关闭响应输出流
out.close();
}
查看图片前台方法:
<a href="javascript:void(0)" class="btn btn-xs btn-primary btn-outline" 

onclick="look(${it?.id})">查看</a>
function look(id) {
    var srcPath = '/valuationHistoryForNSQ/look?id='+id
    var imgPath = '<img src="'+srcPath+'" width="800px" height="500px">'
    layer.open({
        type: 1 //Page层类型
        ,area: ['800px', '542px']
        ,title: '查看'
        ,scrollbar: false //屏蔽浏览器滚动条
        ,shade: 0.6 //遮罩透明度
        ,maxmin: false //允许全屏最小化
        ,anim: 5 //0-6的动画形式,-1不开启
        ,content: imgPath
});
}

grails文件下载,注意中文乱码问题,我的文件路径、文件名称是从数据库查出来的。

我用的win10系统,值得注意的是win10 ie和edge与其他浏览器的区别

相关标签: grails文件下载