微信小程序文件上传(唤起文件资源管理器)

问题

在微信小程序开发开发中,可能会遇到需要上传文件的场景,用户需要从手机文件管理器中选择文件,然后上传到服务器.但是微信小程序只支持选择回话中的文件,无法从手机中选择

方案

我们可以通过小程序的web-view实现.通过html的实现文件上传.

代码

这个代码是基于微信小程序的,当前集成在一个组件中。上传一个文件就会返回到组件中。

web-view页面

<template>
  <web-view
    class="web-view"
    @message="message"
    :src="src"
  ></web-view>
</template>

<script>
import {
    HOMEINDEX_NAME, ACCESS_TOKEN, CURRENT_URL } from "@/common/util/constants"
export default {
   
  name: 'JkyJeecgSlpzWxIdentification',

  data() {
   
    return {
   
      src: ``,
      prevKey: ''
    };
  },
  onLoad(options) {
   
    this.prevKey = JSON.parse(decodeURIComponent(options.query)).prevKey
    let baseUrl = this.$config.identificationUrl + '/' + uni.getStorageSync(CURRENT_URL)
    let token = uni.getStorageSync(ACCESS_TOKEN)
    this.src = this.$config.identificationUrl + `/fileUpload/index.html?baseUrl=` + baseUrl + `&token=` + token
    console.log(this.src, 'this.src')
  },
  created() {
   
  },
  beforeMount() {
   
  },
  mounted() {
   
  },
  methods: {
   
    message(arg) {
   
      console.log(arg, '接收h5页面发来的消息')
      let pages = getCurrentPages();
      let prev = pages[pages.length - 2]; //上一页
      if (this.prevKey) {
   
        if (arg.target.data[0].message == '上传成功') {
   
          prev.$vm[this.prevKey + 'Msg'] = '上传成功'
          prev.$vm[this.prevKey] = arg.target.data[0].url
        } else if (arg.target.data[0].message == '上传失败') {
   
          prev.$vm[this.prevKey + 'Msg'] = '上传失败'
        }
      }
    },
  },
};
</script>

<style lang="less" scoped>
</style>

my-file-upload.vue

<template>
  <view>
    <l-file
      ref="lFile"
      :prevKey="prevKey"
      :logo="logo"
      @up-success="onSuccess"
    ></l-file>
    <button
      type="primary"
      size="mini"
      @click="upload"
      v-if="!disabled"
    >文件上传</button>
    <view>
      <view
        class="cu-form-group"
        v-for="(item,index) in fileList"
        :key="index"
        :data-url="item"
      >
        <view
          class="text_fileName"
          @tap.stop="reviewFile(item)"
        >{
   {
   item}}</view>
        <view
          v-if="!disabled"
          class="cu-tag"
          @tap.stop="DelImg"
          :data-index="index"
        >
          <uni-icons
            type="clear"
            color="#c0c4cc"
            size="24"
          ></uni-icons>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import {
    ACCESS_TOKEN, CURRENT_URL } from '@/common/util/constants.js'
export default {
   
  name: 'MyFileUpoad',
  props: {
   
    prevKey: {
    type: String },
    disabled: {
   
      type: Boolean,
      default: () => {
   
        return false
      }
    },
    value: {
    type: String },
    size: {
    //文件大小限制
      type: Number,
      default: () => {
   
        return 100
      }
    },
    extName: {
    //文件大小限制
      type: Array,
      default: () => {
   
        return [".docx", ".doc", ".rtf", ".txt", ".xltx", ".xls", ".xlsm", ".xlsb", ".csv", ".xml", ".pptx", ".ppt", ".xps", ".pdf", ".jpg", ".png", ".jpeg", ".odf", ".tiff", ".svg", ".zip", ".rar", ".xlsx"]
      }
    },
  },
  mounted: function () {
   
  },
  data() {
   
    return {
   
      logo: 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fbpic.588ku.com%2Felement_origin_min_pic%2F00%2F00%2F07%2F155788a6d8a5c42.jpg&refer=http%3A%2F%2Fbpic.588ku.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1619847627&t=2da40b583002205c204d980b54b35040',
      header: '',
      fileList: [],
      pathlist: [],
      uploadUrl: "/sys/common/upload",
      downLoadUrl: "/sys/common/static/",
      num: 0
    }
  },
  watch: {
   
    value: {
   
      handler(val) {
   
        console.log(val, 79)
        if (val && !this.num) {
   
          this.fileList = val.split(',');
          this.num++;
        }
      },
      deep: true,
      immedaite: true
    }
  },
  created() {
   
    if (this.value) {
   
      this.fileList = this.value.split(',');
    }
  },
  methods: {
   
    reviewFile(item) {
   
      let fileType = item.split('.')[item.split('.').length - 1]
      let url = this.$config.apiUrl + uni.getStorageSync(CURRENT_URL) + this.downLoadUrl + item
      /* 下载返回临时路径(退出应用失效) */
      this.$refs.lFile.download({
    url })
        .then(path => {
   
          /* 打开附件 */
          this.$refs.lFile.open(path, fileType);
        });
    },
    onWebViewSuccess(path) {
   
      if (path) {
   
        this.pathlist.push(path);
        this.$emit('file-change', this.pathlist.join(','))
        if (this.fileList.length != 0) {
   
          this.fileList = this.fileList.concat([path])
        } else {
   
          this.fileList.push(path)
        }
      } else {
   
        uni.showToast({
   
          title: `上传失败`
        })
      }
    },
    onSuccess(res) {
   
      if (res.data.success) {
   
        let path = res.data.message;
        this.pathlist.push(path);
        this.$emit('file-change', this.pathlist.join(','))
        if (this.fileList.length != 0) {
   
          this.fileList = this.fileList.concat([path])
        } else {
   
          this.fileList.push(path)
        }
      } else {
   
        uni.showToast({
   
          title: `上传失败`
        })
      }
    },
    // 选择上传触发函数
    upload() {
   
      let that = this
      this.$refs.lFile.upload({
   
        //替换为你的上传接口地址
        url: that.$config.apiUrl + uni.getStorageSync(CURRENT_URL) 

你可能感兴趣的:(微信小程序,notepad++,小程序)