The back-end returns url to preview and download files (currently only supports images and pdf documents)

A node+express project that I recently contacted needs to have an online preview and download function. After a lot of effort, I finally wrote almost the same. Here is a summary:
One: First, preview through url (you may also preview word and xlsx files in the future, this method cannot be used, and you have to find another method)
  1. This time, the interface is not called, but there is a preview button in the operation column of the list. Then the backend returns the url, type, and id of the file to us in each piece of data in the list.
  2. When you click the preview, you need a pop-up box to display, here is the modal box of layui
  3. We get the file url, and when the popup is completed, assign the url to the element in the popup. (In our project, we want to preview N files, so the carousel component used in the pop-up box)
  4. Judge the file type when assigning, if it is a picture: assign to src of img; if it is pdf: assign to data of object
  5. As long as the url is assigned a value, as long as the url can be used, you can preview it without accident (you can debug it yourself if it involves styles)
Two: The second is to use the preview URL to achieve the download function. (Pro-test pictures and pdf are feasible)
  1. Because this url is for previewing, it is not possible to use ordinary a links, iframes, etc.
  2. After getting the path, you can turn it on the front end first, turn it into a file stream, and then use the a link to download
Three: texture

Insert picture description here

Four: Paste the code (this is the code in my own project, you can just look at the above ideas)
<!-- 预览弹框 -->
<div id="previewBox" style="display: none;">
    <div class="layui-carousel" id="test1">
        <div class="previewCarousel" carousel-item style="overflow: scroll;">
			<!-- 预览的内容 -->
        </div>
    </div>
</div>

// 文件预览
    function filePreview(data) {  // data是列表数据
        // 点击预览按钮
        $('.previewApt').on('click',function(){
            var qInfoIDFlag = $(this).data('flie');
            var attachmentArr = [];
            data.forEach(function(item){
                if(item.QInfoID == qInfoIDFlag){
                    attachmentArr = item.Attachment;
                    return;
                }
            })
            $('#test1 .previewCarousel').empty(); // 销毁预览容器里的所有元素
            var addOpenedit = layer.open({
                type: 1,
                title: "预览",
                closeBtn: 1,
                skin: "pop-set",
                area: ["1000px","700px"],
                maxHeight:"800px",
                moveType: 1,
                resize: false,
                isOutAnim: true,
                scrollbar: true,
                anim: 1,
                content: $('#previewBox').html(),
                success: function (layero, index) {
                    var children = '',content = '';
                    attachmentArr.forEach(function(item){
                        if(item.FileSuffix == 'pdf'){
                            content = '<div><div style="width: 100%;height: 30px;line-height: 30px;text-align: center;font-size: 18px;font-weight: 700;">'+item.FileName+'.'+item.FileSuffix+'<a data-flieurl="'+item.WaterUrl+'" data-fliename="'+item.FileName+'.'+item.FileSuffix+'" class="downloadFlie" style="color: blue;font-size: 12px;font-weight: 500;margin-left: 50px;cursor: pointer;">点击下载...</a></div><object type="text/x-scriptlet" data="'+item.WaterUrl+'" width=100% height=570 id="content_info"></object></div>'
                        }else{
                            content = '<div><div style="width: 100%;height: 30px;line-height: 30px;text-align: center;font-size: 18px;font-weight: 700;">'+item.FileName+'.'+item.FileSuffix+'<a data-flieurl="'+item.WaterUrl+'" data-fliename="'+item.FileName+'.'+item.FileSuffix+'" class="downloadFlie" style="color: blue;font-size: 12px;font-weight: 500;margin-left: 50px;cursor: pointer;">点击下载...</a></div><img style="width: 100%;" src="'+item.WaterUrl+'"  alt="附件预览" /></div>'
                        }
                        children += '<div>'+content+'</div>';
                    })
                    $('#test1 .previewCarousel').append(children);
                    //建造实例
                    carousel.render({
                        elem: $(layero).find('#test1')
                        ,width: '100%' //设置容器宽度
                        ,arrow: 'always' //始终显示箭头
                        ,height:'620px'
                        ,autoplay:false
                        ,anim: 'fade' //切换动画方式
                    });
                    $(layero).find('.downloadFlie').on('click',function(){
                        var flieurl = $(this).data('flieurl');
                        var fliename = $(this).data('fliename');
                        getFileAndDownload(fliename,flieurl);
                    })
                    // console.log(layero, index);
                    $(layero).find('.returnBtn').on('click', function () {
                        layer.close(index);
                    })
                 	$(layero).find('.register-sub a').attr('href','javascript:void(0)').on('click', function () {
                        layer.close(index);
                    })

                    // 下载方法
                    function getFileAndDownload(fileName, url) {
                        var x = new XMLHttpRequest();
                        x.open("GET", url, true);
                        x.responseType = 'blob';
                        x.onload = function (e) {
                            var blob = x.response;
                            if ('msSaveOrOpenBlob' in navigator) {//IE导出
                                window.navigator.msSaveOrOpenBlob(blob, fileName);
                            }
                            else {
                                var a = document.createElement('a');
                                a.download = fileName;
                                a.href = URL.createObjectURL(blob);
                                $("body").append(a);
                                a.click();
                                $(a).remove();
                            }
                        };
                        x.send();
                    }
                }
            });

        })
    }

Guess you like

Origin blog.csdn.net/weixin_43996999/article/details/104531594