上传

在这里插入图片描述

上传页面

		<u-form-item :label="(form.ququ3 == 1 ? '参培' : form.ququ3 == 2 ? '授课' : '') + '证明材料'" prop="ququ6" required>
          <u-button @click="upload" slot="right" type="primary" icon="arrow-upward" text="上传文件" size="small"&gt;</u-button>
        </u-form-item>
        <view class="red">只能上传视频pdf文件支持.pdf, .mp4, .avi, .ts</view>
        <view v-for="(item, i) in form.ququ6" :key="i" class="mb-20 flex ">
          <view class="flex_l" @click="preview(item)">
            <image style="width: 46rpx;height: 46rpx;"
              :src="item.split('.')[item.split('.').length - 1] == 'pdf' ? '/static/pdf.png' : '/static/video.png'">
            </image>
            <view class="blue ml-20 u-line-1 flex-1 over-hidden">{{ item.split('-')[item.split('-').length - 1] }}</view>
          </view>
          <!-- <view class="blue" @click="preview(item)">预览</view> -->
        </view>


import { uploadFile } from '../../common/common'
upload() {
   uploadFile(6).then(res => {
      console.log(2222, res)
      this.form.ququ6 = this.form.ququ6.concat(res)
   })
},

上传方法

/**
 * 上传视频pdf文件
 * @param {*} count 个数
 * @returns arr-- 最终结果   ['img','img']
 */
export let uploadFile = (count = 1) => {
	return new Promise((resolve, reject) => {
		uni.chooseFile({
			count: count,
			extension: ['.pdf', '.mp4', '.avi', '.ts'],
			success: function (res) {
				uni.showLoading({
					title: '上传中'
				})
				let imgarr = res.tempFilePaths
				let arr = []
				imgarr.forEach(item => {
					uni.uploadFile({
						url: '/prod-api' + '/file/upload',
						filePath: item,
						name: 'file',
						header: {
							Authorization: uni.getStorageSync('token') || ''
						},
						success: (res) => {
							console.log(JSON.parse(res.data))
							arr.push(JSON.parse(res.data).data.url)
							if (arr.length == imgarr.length) {
								uni.hideLoading()
								let arr1 = arr.filter(item => ['pdf', 'mp4', 'avi', 'ts'].includes(item.split('.')[item.split('.').length - 1]))
								if (arr1.length != arr.length) {
									uni.showToast({
										title: '只能上传视频pdf文件',
										icon: 'none'
									})
								}
								resolve(arr1)
							}
						},
						fail: () => {
							uni.showToast({
								title: '上传失败',
								icon: 'none'
							})
						}
					});
				})
			}
		});
	})
}

整个页面静态

<template>
  <view class="ptb-20 plr-30 bg min100">
    <view class="bg-white radius-20 pd-30">
      <u--form labelPosition="left" :model="form" :rules="rules" ref="uForm" labelWidth="100">
        <u-form-item label="培训主题名" prop="ququ1" required>
          <u--input v-model="form.ququ1" disabledColor="#ffffff" placeholder="请输入主题名" border="none"></u--input>
        </u-form-item>
        <u-form-item label="培训分类" prop="ququ2" required @click="showPop(1)">
          <u--input class="disabled" v-model="form.ququ2" disabled disabledColor="#ffffff" placeholder="请选择培训分类"
            border="none"></u--input>
          <u-icon slot="right" name="arrow-right"></u-icon>
        </u-form-item>
        <u-form-item label="本人所属类别" prop="ququ3" required>
          <u-radio-group v-model="form.ququ3" placement="row">
            <u-radio class="mr-20" label="参培人" name='1'></u-radio>
            <u-radio label="授课人" name='2'></u-radio>
          </u-radio-group>
        </u-form-item>
        <u-form-item label="参与地点" prop="ququ4">
          <u--input v-model="form.ququ4" placeholder="请输入参与地点" border="none"></u--input>
        </u-form-item>
        <u-form-item label="起止日期" prop="ququ5" @click="showPop(2)" required>
          <u--input class="disabled" v-model="form.ququ5" disabled disabledColor="#ffffff" placeholder="请选择起止日期"
            border="none"></u--input>
          <u-icon slot="right" name="arrow-right"></u-icon>
        </u-form-item>
        <u-form-item :label="(form.ququ3 == 1 ? '参培' : form.ququ3 == 2 ? '授课' : '') + '证明材料'" prop="ququ6" required>
          <u-button @click="upload" slot="right" type="primary" icon="arrow-upward" text="上传文件" size="small"></u-button>
        </u-form-item>
        <view class="red">只能上传视频pdf文件支持.pdf, .mp4, .avi, .ts)</view>
        <view v-for="(item, i) in form.ququ6" :key="i" class="mb-20 flex ">
          <view class="flex_l" @click="preview(item)">
            <image style="width: 46rpx;height: 46rpx;"
              :src="item.split('.')[item.split('.').length - 1] == 'pdf' ? '/static/pdf.png' : '/static/video.png'">
            </image>
            <view class="blue ml-20 u-line-1 flex-1 over-hidden">{{ item.split('-')[item.split('-').length - 1] }}</view>
          </view>
          <!-- <view class="blue" @click="preview(item)">预览</view> -->
        </view>
        <u-form-item label="备注" prop="ququ7">
          <u--textarea v-model="form.ququ7" placeholder="请输入备注" maxlength="150" count autoHeight
            border="none"></u--textarea>
        </u-form-item>
      </u--form>
      <!-- 下拉选择框 -->
      <u-action-sheet :show="show" :actions="actions" title="请选择" @close="close" @select="confirmSelect">
      </u-action-sheet>
      <!-- 日历选择范围 -->
      <u-calendar :maxDate="maxDate" :minDate="minDate" monthNum="10" :show="showDate" mode="range" @confirm="confirmDate"
        @close="close"></u-calendar>
      <view class="flex mt-60">
        <u-button @click="reset">重置</u-button>
        <u-button type="primary" plain class="mlr-20" @click="save">保存草稿</u-button>
        <u-button type="primary" @click="submit">提交审核</u-button>
      </view>
    </view>
  </view>
</template>

<script>
import { uploadFile } from '../../common/common'
const d = new Date()
const year = d.getFullYear()
let month = d.getMonth() + 1
month = month < 10 ? `0${month}` : month
const date = d.getDate()
export default {
  data() {
    return {
      show: false,
      type: null,
      actions: [],

      showDate: false, // 日期选择
      maxDate: `${year}-${month + 1}-${date}`,
      minDate: `${year}-${month - 8}-${date}`,
      form: {
        ququ1: '',
        ququ2: '',
        ququ2Id: '',
        ququ3: '',
        ququ4: '',
        ququ5: '',
        ququ6: [],
        ququ7: '',
      },
      rules: {
        'ququ1': {
          required: true,
          message: '请输入主题名',
          trigger: ['blur']
        },
        'ququ2': {
          required: true,
          message: '请选择培训分类',
          trigger: ['blur', 'change']
        },
        'ququ3': {
          required: true,
          message: '请选择所属类别',
          trigger: ['blur', 'change']
        },
        'ququ5': {
          required: true,
          message: '请选择起止日期',
          trigger: ['blur', 'change']
        },
      },
    };
  },
  onLoad() {

  },
  methods: {
    showPop(type) {
      this.type = type
      if (type == 1) {
        this.show = true
        this.actions = [{
          name: '培训分类1',
          id: 1
        },
        {
          name: '培训分类2',
          id: 2
        },
        ]
      } else {
        this.showDate = true
      }
    },
    close() {
      this.show = false
      this.showDate = false
      this.type = null
    },
    confirmSelect(e) {
      this.form['ququ2'] = e.name
      this.form['ququ2Id'] = e.id
      this.$refs.uForm.validateField('ququ2')
    },
    confirmDate(e) {
      console.log(e);
      this.form['ququ5'] = e[0] + '~' + e[e.length - 1]
      this.showDate = false
    },
    upload() {
      uploadFile(6).then(res => {
        console.log(2222, res)
        this.form.ququ6 = this.form.ququ6.concat(res)
      })
    },
    preview(item) {
      if (item.split('.')[item.split('.').length - 1] == 'pdf') {
        uni.navigateTo({
          url: '/pages/course/pdf?url=' + item
        })
      } else {
        // uni.navigateTo({
        //   url: '/pages/course/video?url=' + item
        // })
        window.open(item)
      }
    },
    submit() {
      this.$refs.uForm.validate().then(res => {
        if (!this.form.ququ6.length) {
          uni.$u.toast('请上传证明材料')
          return
        }
        uni.$u.toast('校验通过')
        this.$http('/system/user/profile', {
          avatar: this.form
        }, "post").then(res => {
          uni.showToast({
            title: '提交成功',
          })
        })
      }).catch(errors => {
        uni.$u.toast('校验失败')
      })
    },
    save() {
      this.$http('/system/user/profile', {
        avatar: this.form
      }, "post").then(res => {
        uni.showToast({
          title: '保存成功',
        })
      })
    },
    reset() {
      this.$refs.uForm.resetFields()
    },
  },

};
</script>

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

预览和下载

在这里插入图片描述

预览页面 PDF预览详见

 <view class="title-left bold mtb-20">附件记录</view>
    <view v-for="(item, i) in form.ququ6" :key="i" class="mb-20 ml-30 flex">
      <view class="flex_l" @click="preview(item)">
        <image style="width: 46rpx;height: 46rpx;"
          :src="item.split('.')[item.split('.').length - 1] == 'pdf' ? '/static/pdf.png' : '/static/video.png'">
        </image>
        <view class="blue ml-20 u-line-1 flex-1 over-hidden">{{ item.split('-')[item.split('-').length - 1] }}</view>
      </view>
      <view class="green" @click="downLoad(item)">下载</view>
    </view>


 data() {
    return {
      form: {
        ququ6: ["https://cscec83-learnplatform.oss-cn-shanghai.aliyuncs.com/test/2023-11-27/6a12b9ca-3ae9-435b-b023-0f9c119afad3-1.mp4", "https://cscec83-learnplatform.oss-cn-shanghai.aliyuncs.com/test/2023-11-27/53aa1f60-0735-4203-86b2-c2b8b019e8d9-我的哈哈.pdf"]
      }
    }
  },

 preview(item) {
      if (item.split('.')[item.split('.').length - 1] == 'pdf') {
        uni.navigateTo({
          url: '/pages/course/pdf?url=' + item
        })
      } else {
        // uni.navigateTo({
        //   url: '/pages/course/video?url=' + item
        // })
        window.open(item)
      }
    },
    downLoad(url) {
      if (url.split('.')[url.split('.').length - 1] == 'pdf') {
        window.open(url)
      } else {
        let xhr = new XMLHttpRequest();
        xhr.open('GET', url, true);
        xhr.responseType = 'blob'; // 返回类型blob
        xhr.onload = function () {
          if (xhr.readyState === 4 &amp;&amp; xhr.status === 200) {
            let blob = this.response;
            // 转换一个blob链接
            let u = window.URL.createObjectURL(new Blob([blob]));
            let a = document.createElement('a');
            a.download = url.split('-')[url.split('-').length - 1]; //下载保存名称
            a.href = u;
            a.style.display = 'none';
            document.body.appendChild(a);
            a.click();
            a.remove();
            uni.hideLoading();
          }
        };
        xhr.send()
      }
    },

详情页面静态

<template>
  <view class="mlr-30 pt-20">
    <view class="title-left bold mb-20">培训详情</view>
    <u-cell-group :border="false">
      <u-cell :border="false" title="培训主题名" :value="userInfo.nickName"></u-cell>
      <u-cell :border="false" title="培训分类" :value="userInfo.sex"></u-cell>
      <u-cell :border="false" title="本人所属类别" :value="userInfo.sex == 1 ? '参培人' : '授课人'"></u-cell>
      <u-cell :border="false" title="起止日期" :value="userInfo.phonenumber"></u-cell>
      <u-cell :border="false" title="参与地点" :value="userInfo.nickName"></u-cell>
      <u-cell :border="false" title="提交时间" :value="userInfo.nickName"></u-cell>
    </u-cell-group>
    <view class="title-left bold mtb-20">附件记录</view>
    <view v-for="(item, i) in form.ququ6" :key="i" class="mb-20 ml-30 flex">
      <view class="flex_l" @click="preview(item)">
        <image style="width: 46rpx;height: 46rpx;"
          :src="item.split('.')[item.split('.').length - 1] == 'pdf' ? '/static/pdf.png' : '/static/video.png'">
        </image>
        <view class="blue ml-20 u-line-1 flex-1 over-hidden">{{ item.split('-')[item.split('-').length - 1] }}</view>
      </view>
      <view class="green" @click="downLoad(item)">下载</view>
    </view>
    <view class="title-left bold mb-20">审批详情</view>
    <u-cell-group :border="false">
      <u-cell :border="false" title="审批状态" :value="userInfo.nickName"></u-cell>
      <u-cell :border="false" title="当前审批人" :value="userInfo.sex"></u-cell>
    </u-cell-group>
    <view class="flex mt-60">
      <u-button @click="back">返回首页</u-button>
      <u-button type="primary" plain class="mlr-20" @click="edit">修改</u-button>
      <u-button type="primary" @click="revoke">撤回流程</u-button>
    </view>
  </view>
</template>

<script>
import {
  mapState
} from 'vuex'
export default {
  data() {
    return {
      form: {
        ququ6: ["https://cscec83-learnplatform.oss-cn-shanghai.aliyuncs.com/test/2023-11-27/6a12b9ca-3ae9-435b-b023-0f9c119afad3-1.mp4", "https://cscec83-learnplatform.oss-cn-shanghai.aliyuncs.com/test/2023-11-27/53aa1f60-0735-4203-86b2-c2b8b019e8d9-我的哈哈.pdf"]
      }
    }
  },
  computed: {
    ...mapState(['userInfo']),
  },
  onLoad() {
    // 刷新个人信息
    this.$store.dispatch('updateUserInfo')
    this.img = this.userInfo.avatar ? this.userInfo.avatar : '/static/user-default.png'
  },
  methods: {
    preview(item) {
      if (item.split('.')[item.split('.').length - 1] == 'pdf') {
        uni.navigateTo({
          url: '/pages/course/pdf?url=' + item
        })
      } else {
        // uni.navigateTo({
        //   url: '/pages/course/video?url=' + item
        // })
        window.open(item)
      }
    },
    downLoad(url) {
      if (url.split('.')[url.split('.').length - 1] == 'pdf') {
        window.open(url)
      } else {
        let xhr = new XMLHttpRequest();
        xhr.open('GET', url, true);
        xhr.responseType = 'blob'; // 返回类型blob
        xhr.onload = function () {
          if (xhr.readyState === 4 &amp;&amp; xhr.status === 200) {
            let blob = this.response;
            // 转换一个blob链接
            let u = window.URL.createObjectURL(new Blob([blob]));
            let a = document.createElement('a');
            a.download = url.split('-')[url.split('-').length - 1]; //下载保存名称
            a.href = u;
            a.style.display = 'none';
            document.body.appendChild(a);
            a.click();
            a.remove();
            uni.hideLoading();
          }
        };
        xhr.send()
      }
    },
    revoke() {
      this.$http('/system/user/profile', {
        avatar: 1
      }, "put").then(res => {
        uni.showToast({
          title: '撤回成功',
        })
      })
    },
    edit() {
      uni.navigateTo({
        url: './add?id=1'
      })
    },
    back() {
      uni.navigateBack()
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .u-cell__body {
  padding: 5px 15px !important;
}
</style>

完整的上传视频、上传pdf、上传图片 方法封装需要传递name、size、时长)

/**
 *  上传图片
 *  count-- 可选张数
 * 	arr-- 最终结果   ['img','img']
 */
export let upload = (count = 1) => {
	console.log(count);
	return new Promise((resolve, reject) => {
		uni.chooseImage({
			count: count,
			sizeType: ['original', 'compressed'], //可以指定原图还是压缩图,默认二者都有
			success: function (res) {
				uni.showLoading({
					title: '上传中'
				})
				let imgarr = res.tempFilePaths
				let arr = []
				imgarr.forEach(item => {
					uni.uploadFile({
						url: '/prod-api' + '/file/upload',
						filePath: item,
						name: 'file',
						header: {
							Authorization: uni.getStorageSync('token') || ''
						},
						success: (res) => {
							console.log(JSON.parse(res.data))
							uni.hideLoading()
							arr.push(JSON.parse(res.data).data.url)
							if (arr.length == imgarr.length) {
								resolve(arr)
							}
						},
						fail: () => {
							uni.showToast({
								title: '上传失败',
								icon: 'none'
							})
						}
					});
				})
			}
		});
	})
}
/**
 * 上传pdf文件
 * @param {*} count 个数
 * @returns arr-- 最终结果   ['img','img']
 */
export let uploadFile = (count = 1) => {
	return new Promise((resolve, reject) => {
		uni.chooseFile({
			count: count,
			extension: ['.pdf'],
			success: function (res) {
				console.log(888, res)
				uni.showLoading({
					title: '上传中'
				})
				let imgarr = res.tempFiles
				let arr = []
				imgarr.forEach(item => {
					uni.uploadFile({
						url: '/prod-api' + '/file/appUpload', //接口地址
						filePath: item.path, // 上传文件参数
						name: 'file', // 上传文件参数
						formData: {  // 额外参数
							fileName: item.name,
							size: (item.size / 1024 / 1024).toFixed(2),
							type: 'pdf',
						},
						header: { //请求
							Authorization: uni.getStorageSync('token') || ''
						},
						success: (res) => {
							arr.push(JSON.parse(res.data).data)
							if (arr.length == imgarr.length) {
								uni.hideLoading()
								let arr1 = arr.filter(item => 'pdf' == item.fileName.split('.')[item.fileName.split('.').length - 1])
								if (arr1.length != arr.length) {
									uni.showToast({
										title: '只能上传pdf文件',
										icon: 'none'
									})
								}
								resolve(arr1)
							}
						},
						fail: () => {
							uni.showToast({
								title: '上传失败',
								icon: 'none'
							})
						}
					});
				})
			}
		});
	})
}
/** 上传视频
 * 	arr-- 最终结果   [{img1:'全路径',img2:'半路径'},{img1:'全路径',img2:'半路径'}]
 */
export let uploadVideo = () => {
	return new Promise((resolve, reject) => {
		uni.chooseVideo({
			count: 1,
			success: function (res) {
				uni.showLoading({
					title: '上传中'
				})
				console.log(111111111111, res)
				uni.uploadFile({
					url: '/prod-api' + '/file/appUpload', //接口地址
					filePath: res.tempFilePath, // 上传文件参数
					name: 'file', // 上传文件参数
					formData: {  // 额外参数,formData传参
						fileName: res.name,
						size: (res.size / 1024 / 1024).toFixed(2),
						duration: res.duration,
						type: 'video',
					},
					header: { //请求
						Authorization: uni.getStorageSync('token') || ''
					},
					success: (res) => {
						uni.hideLoading()
						if (JSON.parse(res.data).code == '200') {
							resolve(JSON.parse(res.data).data)
						} else {
							uni.showToast({
								title: JSON.parse(res.data).msg,
								icon: 'none'
							})
						}
					},
					fail: () => {
						uni.showToast({
							title: '上传失败,请重试',
							icon: 'none'
						})
					}
				});
			}
		});
	})
}

原文地址:https://blog.csdn.net/weixin_43848576/article/details/134646978

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_20792.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注