小程序上傳各種文件,閱覽多種格式(word,excel,ppt,pdf)文件

我們用小程序與網站交互,那麼無非是上傳文件,發佈文章,閱覽文件(主要是office和pdf)和文章。

服務端用engineercms,各種文件分類在網站上展示是這樣的:

 可見,有文章,有附件——word格式等,有pdf格式。

小程序支持閱覽多種office格式文件

官方列出有:https://developers.weixin.qq.com/miniprogram/dev/api/file/wx.openDocument.html

doc doc 格式  
docx docx 格式  
xls xls 格式  
xlsx xlsx 格式  
ppt ppt 格式  
pptx pptx 格式  
pdf pdf 格式

 所以就可以將服務端混排的各種附件和文章進行混排展示出來,如下圖:

當點擊文件時,就跳轉到文件閱覽頁,當點擊文章時候,就跳轉到文件詳情頁。 

小程序列表 模板切換用官方下面的代碼

https://developers.weixin.qq.com/miniprogram/dev/reference/wxml/template.html

<template name="odd">
  <view> odd </view>
</template>
<template name="even">
  <view> even </view>
</template>

<block wx:for="{{[1, 2, 3, 4, 5]}}">
  <template is="{{item % 2 == 0 ? 'even' : 'odd'}}"/>
</block>

 各種文件擴展名用下面這個工具製作了圖標:

https://github.com/joaner/namedavatar

小程序代碼:

js

//直接查看各種文件
  downloadFile: function (e) {
    wx.showLoading({
      title: '加載中...',
    })

    var that = this;
    if (that.data.standardFocus) {
      that.setData({
        downloadurl: config.url + '/wx/wxstandardpdf/' + e.currentTarget.dataset.id,
      });
    } else {
      that.setData({
        downloadurl: config.url + '/wx/getwxpdf/' + e.currentTarget.dataset.id,
      });
    };
    var sessionId = wx.getStorageSync('sessionId')
    //發起網絡請求
    wx.downloadFile({
      url: that.data.downloadurl + '?hotqinsessionid=' + sessionId,
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function (res) {
        console.log(res.tempFilePath)
        const filePath = res.tempFilePath //返回的文件臨時地址,用於後面打開本地預覽所用
        wx.openDocument({
          filePath: filePath,
          fileType: e.currentTarget.dataset.type,
          success: function (res) {
            console.log('打開成功');
            wx.hideLoading()
          },
          fail: function (res) {
            // console.log(res);
            wx.showToast({
              title: res.data.info,
              icon: 'loading',
              duration: 1500
            })
          }
        })
      },
      fail: function (res) {
        console.log(res);
        wx.showToast({
          title: res.data.info,
          icon: 'loading',
          duration: 1500
        })
      },
    })
  },

 wxml

<template name="msgTemp">
		<view class="weui-panel__bd">
			<!-- <navigator class="weui-media-box weui-media-box_appmsg" hover-class="weui-cell_active"> -->
			<view class="weui-media-box weui-media-box_appmsg" hover-class="weui-cell_active">
				<view class="weui-media-box__hd weui-media-box__hd_in-appmsg">
					<image class="weui-media-box__thumb" src="{{Link}}" style="width: 60px; height: 60px;" style="border-radius: 100%" />
					<!-- <wxc-avatar class="avatar">圖</wxc-avatar> -->
				</view>
				<view class="weui-media-box__bd weui-media-box__bd_in-appmsg" data-id="{{Id}}" data-type="{{Type}}" catchtap='downloadFile'>
					<view class="weui-media-box__title">{{Title}}</view>
					<view class="weui-media-box__desc">{{tutil.formatTime(Created)}}</view>
					<view class="weui-media-box__desc">{{LiNumber}}</view>
				</view>
				<navigator class="weui-media-box__desc" url="../pdfview/pdfview?id={{Id}}&title={{Title}}&actIndex={{ActIndex}}&link={{Link}}&type={{Type}}">分享</navigator>
				<!-- </navigator> -->
			</view>
		</view>
	</template>

	<!--用name 定義模版-->
	<template name="article">
		<view class='leassonList' data-id="{{Id}}" bindtap="seeDetail">
			<view class='listIn'>
				<view class='leassonImg'>
					<image src="{{Link}}" class='leassonImgs' mode='aspectFill' />
					<!-- <image class="weui-media-box__thumb" src="{{Link}}" style="width: 60px; height: 60px;" style="border-radius: 100%" /> -->
				</view>
				<view class='leassonTitle'>
					<view class='title'>
						{{Title}}
					</view>
					<view class='author'>
						作者:{{Author}}
					</view>
				</view>
			</view>
		</view>
	</template>

			<view wx:for-items="{{msgList}}" wx:key="{{item.id}}">
				<view class="kind-list__item">
					<!--用is 使用模版-->
					<template is="{{item.Type=='isArticle'?'article':'msgTemp'}}" data="{{...item}}" />
				</view>
			</view>

服務端engineercms返回數據爲下所示:其中Link,當爲文件時,用圖標的base64,爲文章時,用文章裏的第一個圖片。

{
  "info": "SUCCESS",
  "searchers": [
    {
      "Id": 15,
      "Title": "珠三角工程模擬飛檢設計整改報告和有關說明珠三角工程模擬飛檢設計整改報告和有關說明.docx",
      "Type": "docx",
      "Link": "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMDAiIGhlaWdodD0iMTAwIj48cmVjdCBmaWxsPSIjRkY1NzIyIiB4PSIwIiB5PSIwIiB3aWR0aD0iMTAwJSIgaGVpZ2h0PSIxMDAlIj48L3JlY3Q+PHRleHQgZmlsbD0iI0ZGRiIgeD0iNTAlIiB5PSI1MCUiIHRleHQtYW5jaG9yPSJtaWRkbGUiIGZvbnQtc2l6ZT0iNTAiIGZvbnQtZmFtaWx5PSJzYW5zLXNlcmlmIiBhbGlnbm1lbnQtYmFzZWxpbmU9Im1pZGRsZSI+VzwvdGV4dD48L3N2Zz4=",
      "Subtext": "",
      "Author": "",
      "Created": "2020-06-25T11:54:41.4978218Z",
      "Updated": "2020-06-25T11:54:41.4978218Z"
    },
    {
      "Id": 19,
      "Title": "魯班測試993",
      "Type": "isArticle",
      "Link": "http://127.0.0.1/attachment/LBGCB魯班工程寶/質量監督/2020June/1593093898342607000.jpg",
      "Subtext": "asdfasdfsadf",
      "Author": "admin",
      "Created": "2020-03-18T14:37:33.5387154Z",
      "Updated": "2020-06-25T14:05:01.7747665Z"
    }
  ]
}

小程序上傳各種文件:

 小程序上傳文件js:

  //上傳文件
  uploadPDF(e) {
    var that = this
    that.setData({
      uploadurl: config.url + '/admin/addwxattachment?pid=' + that.data.id,
    });
    wx.chooseMessageFile({
      count: 10,
      type: 'file',
      success(res) {
        const tempFilePaths = res.tempFiles
        if (tempFilePaths.length > 0) {
          wx.showLoading({
            title: '上傳中...',
          })
          //循環比較
          for (var i = 0; i < tempFilePaths.length; i++) {
            var imgUrl = tempFilePaths[i].path;
            var filename = tempFilePaths[i].name;
            var sessionId = wx.getStorageSync('sessionId')
            //發起網絡請求
            wx.uploadFile({
              //上傳圖片的網路請求地址
              url: that.data.uploadurl + '&hotqinsessionid=' + sessionId,
              //選擇
              filePath: imgUrl,
              name: 'file',
              formData: {
                'filename': filename
              },
              success: function (res) {
                wx.hideLoading();
                if (res.data.info != "err") {
                  wx.showToast({
                    title: "上傳成功",
                    icon: "none",
                    duration: 1500
                  })
                  // 加跳轉
                  wx.navigateBack({
                    delta: 1,
                    success: function (e) {
                      var page = getCurrentPages().pop();
                      if (page == undefined || page == null) return;
                      page.onLoad();
                    }
                  })
                } else {
                  wx.showToast({
                    title: "上傳失敗",
                    icon: "none",
                    duration: 1500
                  })
                }
              },
              fail: function (res) {
                wx.hideLoading();
                wx.showToast({
                  title: "文件上傳失敗",
                  icon: "none"
                })
              }
            });
          }
        }
      }
    })
  },

當然,上傳按鈕必須要做2個,一個是上傳文件,一個是發佈文章哦。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章