[uniapp] uniapp上传手机pdf文件

本文介绍了如何在微信小程序中使用uni-file-picker组件上传文件,重点讨论了如何隐藏已上传的PDF文件,以及处理HTTP链接时如何先下载到本地再通过openDocument预览。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

从微信小程序上传文件

上传文件

使用uni-file-picker组件上传代码

<uni-file-picker
  ref="files"
  :auto-upload="false"
  limit="9"
  file-mediatype="all"
  @select="select"
>
  <view>文件上传</view>
</uni-file-picker>
// 上传文件
select(e) {
  this.$refs.popup.close();
  let fullPath = e.tempFilePaths; //图片集合
  let uploadFiles = fullPath.map((item) => {
    return item.substring(item.lastIndexOf(".") + 1).toLowerCase(); //文件后缀小写
  });
  let typeInfo = ["pdf"];
  // 过滤出 uploadFiles 中在 typeInfo 中没有出现过的值
  const notFound = uploadFiles.filter((item) => !typeInfo.includes(item));
  if (notFound.length > 0) {
    uni.showToast({
      title: "目前仅支持pdf文件!",
      icon: "none",
      duration: 2000,
    });
    return false;
  }else{
	  //接口
	  //......
  }
}

在这里插入图片描述

但是这会出现上传的pdf回显在下面

在这里插入图片描述
不想让文件显示,直接把高度设置0

.is-text-box {
  height: 0;
}

显示文件

在这里插入图片描述
我这边是http开头的,所以需要先下载文件资源到本地才能打开

previewImage(url) {
  uni.downloadFile({
    url: url,
    success: function (res) {
      var filePath = res.tempFilePath;
      uni.openDocument({
        filePath: filePath,
      });
    },
  });
},

最后看看成果吧

在这里插入图片描述

uniapp中监听上传PDF文件可以通过以下步骤实现: 1. **上传PDF文件**:使用uni.uploadFile接口将PDF文件上传到服务器。 2. **保存文件路径**:将上传成功后返回的文件路径保存到本地存储或数据库中。 3. **预览PDF文件**:使用uni.openDocument接口在应用中预览上传PDF文件。 以下是一个示例代码,展示了如何实现上述步骤: ```javascript <template> <view> <button @click="uploadPDF">上传PDF文件</button> <button @click="previewPDF">预览PDF文件</button> </view> </template> <script> export default { data() { return { pdfFilePath: '' // 存储PDF文件路径 }; }, methods: { uploadPDF() { uni.chooseFile({ count: 1, type: 'file', success: (res) => { const tempFilePaths = res.tempFilePaths; uni.uploadFile({ url: 'https://your-server.com/upload', // 替换为你的上传接口 filePath: tempFilePaths[0], name: 'file', formData: { 'user': 'test' }, success: (uploadRes) => { const data = JSON.parse(uploadRes.data); // 假设服务器返回文件路径 this.pdfFilePath = data.filePath; uni.showToast({ title: '上传成功', icon: 'success' }); }, fail: (uploadRes) => { uni.showToast({ title: '上传失败', icon: 'none' }); } }); } }); }, previewPDF() { if (this.pdfFilePath) { uni.openDocument({ filePath: this.pdfFilePath, success: (res) => { console.log('打开文档成功'); }, fail: (res) => { console.log('打开文档失败'); } }); } else { uni.showToast({ title: '请先上传PDF文件', icon: 'none' }); } } } }; </script> <style> button { margin: 10px; } </style> ``` ### 解释 1. **上传PDF文件**: - 使用`uni.chooseFile`选择文件- 使用`uni.uploadFile`将文件上传到服务器。 - 上传成功后,将服务器返回的文件路径保存到`pdfFilePath`中。 2. **预览PDF文件**: - 使用`uni.openDocument`打开本地或远程的PDF文件
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值