OpenLayers 文件下载

90 阅读3分钟

前言

在WebGIS系统开发中,通常需要实现文件上传功能,这只是第一步,在实现文件上传进行分析之后,还需要将分析的结果保存下来,这就需要实现文件下载的功能。

1. 文件下载关键代码

文件下载的关键代码在于创建a元素。因为是临时元素,所以将其style属性display设置为"none",并将其添加到body中。之后通过fetch方法读取文件数据,将文件内容转换为blob类型,最后赋值给a元素属性,紧接着将a元素从body中移除。

// 下载文件方法
const linkEle = document.createElement("a")
linkEle.style.display = "none"
document.body.appendChild(linkEle)
function downloadFile(fullPath, fileName) {
    fetch(fullPath)
        .then(response => response.blob())
        .then(blob => {
            linkEle.href = URL.createObjectURL(blob)
            linkEle.download = fileName
            linkEle.click()
            document.body.removeChild(linkEle)
        })
}

2. 完整代码

其中libs文件夹下的包需要更换为自己下载的本地包或者引用在线资源。

<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>OpenLayers 文件下载</title>
    <meta charset="utf-8" />

    <link rel="stylesheet" href="../../libs/css/ol9.2.4.css">

    <script src="../../js/config.js"></script>
    <script src="../../libs/js/ol9.2.4.js"></script>
    <style>
        * {
            padding0;
            margin0;
            font-size14px;
            font-family'微软雅黑';
        }

        html,
        body {
            width100%;
            height100%;
        }

        #map {
            position: absolute;
            top50px;
            bottom0;
            width100%;
        }

        #top-content {
            position: absolute;
            width100%;
            height50px;
            line-height50px;
            backgroundlinear-gradient(135deg#ff00cc#ffcc00#00ffcc#ff0066);
            color#fff;
            text-align: center;
            font-size32px;
        }

        #top-content span {
            font-size32px;
        }

        .download-file {
            position: absolute;
            right50px;
            top80px;
            padding20px 10px;
            color#fff;
            border-radius5px;
            border1px solid #50505040;
            backgroundlinear-gradient(135deg#c850c0#4158d0);
        }

        .upload-shp:hover {
            cursor: pointer;
            filterbrightness(120%);
            backgroundlinear-gradient(135deg#eb3ddf#0931fb);
        }

        .download-btn {
            border-radius5px;
            border1px solid #50505040;
            padding5px 20px;
            color#fff;
            margin0 10px;
            background#4646466e;
            transition: background-color 10s ease-in-out 10s;
        }

        .download-btn:hover {
            cursor: pointer;
            filterbrightness(120%);
            backgroundlinear-gradient(135deg#c850c0#4158d0);
        }
    </style>
</head>

<body>
    <div id="top-content">
        <span>OpenLayers 文件下载</span>
    </div>
    <div id="map" title="地图显示"></div>
    <div class="download-file">
        <span id="download-gpx" class="download-btn">GPX</span>
        <span id="download-json" class="download-btn">GeoJSON</span>
        <span id="download-kml" class="download-btn">KML</span>
    </div>
</body>

</html>

<script>
    //地图投影坐标系
    const projection = ol.proj.get('EPSG:3857');
    //==============================================================================//
    //============================天地图服务参数简单介绍==============================//
    //================================vec:矢量图层==================================//
    //================================img:影像图层==================================//
    //================================cva:注记图层==================================//
    //======================其中:_c表示经纬度投影,_w表示球面墨卡托投影================//
    //==============================================================================//
    const TDTImgLayer = new ol.layer.Tile({
        title"天地图影像图层",
        sourcenew ol.source.XYZ({
            url"http://t0.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=" + TDTTOKEN,
            attibutions"天地图影像描述",
            crossOrigin"anoymous",
            wrapXfalse
        })
    })
    const TDTImgCvaLayer = new ol.layer.Tile({
        title"天地图影像注记图层",
        sourcenew ol.source.XYZ({
            url"http://t0.tianditu.com/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=" + TDTTOKEN,
            attibutions"天地图注记描述",
            crossOrigin"anoymous",
            wrapXfalse
        })
    })
    const map = new ol.Map({
        target"map",
        loadTilesWhileInteractingtrue,
        viewnew ol.View({
            center: [102.84586425.421639],
            zoom6.5,
            worldsWrapfalse,
            minZoom1,
            maxZoom20,
            projection'EPSG:4326',
        }),
        layers: [TDTImgLayer],
        // 地图默认控件
        controls: ol.control.defaults.defaults({
            zoomfalse,
            attributionfalse,
            rotatefalse
        })
    })
    map.on('click'evt => {
        console.log("获取地图坐标:", evt.coordinate)
    })

    // 下载文件方法
    const linkEle = document.createElement("a")
    linkEle.style.display = "none"
    document.body.appendChild(linkEle)
    function downloadFile(fullPath, fileName) {
        fetch(fullPath)
            .then(response => response.blob())
            .then(blob => {
                linkEle.href = URL.createObjectURL(blob)
                linkEle.download = fileName
                linkEle.click()
                document.body.removeChild(linkEle)
            })
    }
    document.querySelector("#download-gpx").addEventListener('click'(evt) => {
        downloadFile("http://localhost/DataSource/location.gpx"'location.gpx')
    })
    document.querySelector("#download-json").addEventListener('click'(evt) => {
        downloadFile("http://localhost/DataSource/lands.json"'lands.json')
    })
    document.querySelector("#download-kml").addEventListener('click'(evt) => {
        downloadFile("http://localhost/DataSource/subway.kml"'subway.kml')
    })
</script>

OpenLayers示例数据下载,请回复关键字:ol数据

全国信息化工程师-GIS 应用水平考试资料,请回复关键字:GIS考试

【GIS之路】 已经接入了智能助手,欢迎关注,欢迎提问。

欢迎访问我的博客网站-长谈GIShttp://shanhaitalk.com

都看到这了,不要忘记点赞、收藏 + 关注

本号不定时更新有关 GIS开发 相关内容,欢迎关注 !