uniapp APP 上传PDF文件

uniapp APP端

文件上传使用plus.io.chooseFile

图片上传使用uni.chooseImage

如果两种需求都存在的情况下使用plus.nativeUI.actionSheet 做一个判断 调用uni.uploadFile实现上传,只不过APP端需要使用plus.io.chooseFile来选取文件调起移动端文件列表

javascript 复制代码
 plus.nativeUI.actionSheet(
    {
      title: "选择上传类型",
      cancel: "取消",
      buttons: [{ title: "选择图片" }, { title: "选择文件" }],
    },
    (e) => {
      switch (e.index) {
        case 1:
          handleChooseImage();
          break;
        case 2:
          handleChooseFile();
          break;
      }
    }
  );

图片上传

javascript 复制代码
const handleChooseImage = async () => {
  const remainCount = getRemainCount();

  try {
    const selectResult = await uni.chooseImage({
      count: remainCount,
      sizeType: ["original", "compressed"],
      sourceType: ["album", "camera"],
    });

    for (const tempFile of selectResult.tempFiles) {
      await uploadSingleFile(tempFile);//上传方法
    }
  } catch (error) {
    const errMsg = error?.errMsg || "";
    if (errMsg && !errMsg.includes("cancel")) {
      uni.showToast({
        title: "选择图片失败:" + errMsg,
        icon: "none",
      });
    }
  }
};

文件上传

javascript 复制代码
const handleChooseFile = async () => {
  try {
    const result = await new Promise((resolve, reject) => {
      plus.io.chooseFile(
        {
          title: "选择文件",
          filter: {
            mimeTypes: ["application/pdf", "image/*"],
            extensions: ["pdf", "jpg", "jpeg", "png", "gif", "bmp", "webp"],
          },
          multiple: true,
          maximum: getRemainCount(),
        },
        (result) => {
          if (!result || !result.files || result.files.length === 0) {
            reject("未选择任何文件");
            return;
          }
          resolve(result);
        },
        (err) => {
          reject("选择文件失败:" + err.message);
        }
      );
    });

    const files = result.files;

    for (const filePath of files) {
      await uploadSingleFile({ path: filePath });
    }
  } catch (error) {
    if (error !== "未选择任何文件" && !error.includes("cancel")) {
      uni.showToast({
        title: typeof error === "string" ? error : "选择文件失败",
        icon: "none",
      });
    }
  }
};

公共方法

javascript 复制代码
const uploadSingleFile = async (tempFile) => {
  let loadingShown = false;
  try {
    const isImage = isImageFile(tempFile);
    const uploadUrl = isImage
      ? getUrl("/api/upload/picture")
      : getUrl("/api/upload/file");
    const fileName = isImage ? "picture" : "file";

    loadingShown = true;
    uni.showLoading({
      title: `正在上传: ${tempFile.path.split("/").pop()}`,
      mask: true,
    });

    const uploadResult = await new Promise((resolve, reject) => {
      uni.uploadFile({
        url: uploadUrl,
        filePath: tempFile.path,
        name: fileName,
        formData: { zip: "1" },
        success: (uploadRes) => {
          try {
            const data = JSON.parse(uploadRes.data);
            if (data.code === 200) {
              resolve(data);
            } else {
              reject(data.message || "上传失败");
            }
          } catch (e) {
            reject("解析上传结果失败");
          }
        },
        fail: (err) => {
          reject("上传失败:" + (err.errMsg || "网络错误"));
        },
      });
    });

    const serverFilePath =
      uploadResult.data?.path || uploadResult.data?.url || uploadResult.path;
    if (serverFilePath) {
      const fileObj = {
        name: tempFile.name || tempFile.path.split("/").pop(),
        path: serverFilePath,
        url: serverFilePath,
        size: tempFile.size || 0,
      };

      if (userInfo[currentUploadField.value].length < 20) {
        userInfo[currentUploadField.value].push(fileObj);
        uni.showToast({
          title: "上传成功",
          icon: "success",
        });
      }
    } else {
      throw new Error("服务器未返回文件路径");
    }
  } catch (error) {
    console.error("上传文件失败:", error);
    throw error;
  } finally {
    if (loadingShown) {
      uni.hideLoading();
    }
  }
};
相关推荐
MY_TEUCK7 小时前
【AI 应用】前端接口联调工程化:把 Swagger 接入沉淀成可复用 Skill
前端·人工智能·uni-app·状态模式
上架ipa8 小时前
uniapp打包ios配置、申请证书、测试和上架综合教程
uni-app
00后程序员张8 小时前
完整指南 iOS App上架到App Store的步骤详解
macos·ios·小程序·uni-app·objective-c·cocoa·iphone
hhzz9 小时前
记录微信小程序tabbar不显示问题:uni-app Vue 3 自定义 tabBar 不渲染
vue.js·微信小程序·uni-app
存在的五月雨9 小时前
uniapp 一些组件的使用
java·前端·uni-app
久爱@勿忘9 小时前
uniappH5跳转小程序
前端·小程序·uni-app
郑州光合科技余经理20 小时前
同城O2O海外版二次开发实战:从支付网关到配送算法
开发语言·前端·后端·算法·架构·uni-app·php
启山智软1 天前
前沿主流技术栈商城系统(Java JDK21 + Vue3 + Uniapp)
java·开发语言·uni-app
WeirdOwl1 天前
uniapp 嵌入外部h5 报错/收不到消息
uni-app
敲代码的鱼哇3 天前
发送短信/拨打电话/获取联系人能力 UTS 插件(cz-sms)
android·前端·ios·uni-app·安卓·harmonyos·鸿蒙