vue+vant移动端上传upload

1 篇文章 0 订阅
1 篇文章 0 订阅

1、首先下载依赖

# Vue 2 项目,安装 Vant 2.x 版本: npm i vant -S

# Vue 3 项目,安装 Vant 3.x 版本: npm i vant@next -S

2、全局或者自己局部引用

(依据自己需求而定)

3、这里使用局部引入组件

import { Uploader } from 'vant';

<template>

//直接使用

<van-uploader :after-read="afterRead" />

//在表单中使用

<van-field name="uploader" label="上传清单">

          <template #input>

            <van-uploader v-model="uploader" :after-read="onRead" :max-count="1"/>

          </template>

</van-field>

</template>

其中after-read是上传回调方法

onRead(file){//上传清单

        var formDate = new FormData();

        formDate.append('file',file.file);

        this.newForm.FileName = file.file.name//保存上传文件名

//通过接口上传文件,并返回文件地址,其中BASE_URL是服务器地址  'file/upload'是上传文件接口

        this.$http.post(BASE_URL+'file/upload',formDate).then(data=>{

          if(data.code==0){

            this.newForm.FileUrl = data.data.Url;

          }

        })

      },

 

 

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用VantUpload组件和pdf.js库来实现移动端的PDF文件上传和预览功能。 首先,在你的Vue项目中安装Vant和pdf.js库: ``` npm install vant pdfjs-dist --save ``` 然后,在你的组件中引入Upload组件和pdf.js库: ```javascript <template> <div> <van-upload :max-count="1" :before-read="beforeRead" :after-read="afterRead" accept="application/pdf" :show-upload="false" > <van-button type="primary">上传文件</van-button> </van-upload> <div ref="pdfContainer"></div> </div> </template> <script> import { Upload, Button } from 'vant' import pdfjsLib from 'pdfjs-dist' export default { components: { VanUpload: Upload, VanButton: Button, }, methods: { beforeRead(file) { // 判断文件类型是否为PDF return file.type === 'application/pdf' }, afterRead(file) { // 读取文件并渲染PDF预览 const reader = new FileReader() reader.readAsArrayBuffer(file) reader.onload = () => { pdfjsLib.getDocument(new Uint8Array(reader.result)).promise.then(pdf => { pdf.getPage(1).then(page => { const canvas = document.createElement('canvas') const scale = 1.5 const viewport = page.getViewport({ scale }) const context = canvas.getContext('2d') canvas.height = viewport.height canvas.width = viewport.width page.render({ canvasContext: context, viewport }).promise.then(() => { this.$refs.pdfContainer.innerHTML = '' this.$refs.pdfContainer.appendChild(canvas) }) }) }) } }, }, } </script> ``` 在上面的代码中,我们使用了VantUpload组件来实现文件上传功能,并且设置了只能上传PDF文件。在afterRead方法中,我们使用pdf.js库来读取上传的PDF文件,并将PDF渲染到页面上。 需要注意的是,pdf.js库会异步加载PDF文件,因此我们需要在Vue组件中使用promise来处理异步操作。此外,为了在页面上显示PDF预览,我们需要使用canvas元素来渲染PDF页面。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值