由于uniapp提供的API在app端只能上传图片视频,不能上传其他文件,说以只能借助插件了。

 ios端用的这个插件 获取文件对象 免费

iosuniapp 文件选取word,pdf,xls文件 – DCloud 插件市场uniapp iOS文件选取 iOS选取text,pdf,word,doc,xls,ppthttps://ext.dcloud.net.cn/plugin?id=1311

这个返回一个 filePath 可用直接用于 uni.uploadFile 上传路径,后面自己又改的File对象

安卓部分主要通过plus 对象,来调用原生文件系统管理器来选取文件,并获取文件的路径和文件对象调用 pickFile.PickFile 方法来选取文件,使用plus.io.resolveLocalFileSystemURL方法。该方法用于本地文件路径转换文件系统 URL,并返回对应的 FileEntry 对象

微信小程序和H5那就简单uniapp提供的API就可以

示例代码

<template>
  <view class="">
    <view class="" @click="sendFile">
      &lt;text>获取文件</text>
    </view>
  </view>
</template>

   methods: {
      sendFile() {
        // #ifdef H5
        uni.chooseFile({
          count: 1,
          // extension:['.zip','.doc'],
          success: (res) => {
            console.log(res);
            console.log('file:', res.tempFiles[0]); // File对象
            // 可以这里进行后续操作
          }
        });
        // #endif

        // #ifdef MP-WEIXIN
        console.log('WEIXIN');
        wx.chooseMessageFile({
          count: 10,
          type: 'file',
          success: (res) => {
            console.log('file:', res.tempFiles[0]); // File对象
            // 可以这里进行后续操作
          }
        })
        // #endif

        // #ifdef APP-PLUS
        switch (uni.getSystemInfoSync().platform) {
          case 'android':
            let permisionID = 'android.permission.READ_EXTERNAL_STORAGE'
            permision.requestAndroidPermission(permisionID)
              .then(res => {
                if (res == 1) {
                  this.chooseFileAndroid()
                } else {
                  uni.showModal({
                    title: '无法访问存储',
                    content: '您已经关闭存储权限,您已经关闭存储权限,请在"设置-隐私-存储"中允许访问存储',
                    success: (res) => {
                      if (res.confirm) {
                        // plus.runtime.openURL("package:");
                      } else if (res.cancel) {
                        plus.runtime.openURL("package:");
                        console.log('用户点击取消');
                      }
                    }
                  });
                }
              })
            break;
          case 'ios':
            this.filePathIos()
            break;
        }
        // #endif
      },

      // ios 选择文件
      filePathIos() {
          // 示例代码:
          const iOSFileSelect = uni.requireNativePlugin('YangChuan-YCiOSFileSelect');
          // apple document-types 文件类型参数 https://developer.apple.com/library/archive/documentation/Miscellaneous/Reference/UTIRef/Articles/System-DeclaredUniformTypeIdentifiers.html
          // 文件类型参数
          let params = {
            "document-types": ["public.text", "public.zip", "public.data", "com.adobe.pdf",
              "com.microsoft.word.doc", "com.adobe.postscript", "com.microsoft.excel.xls",
              "com.adobe.encapsulated- postscript", "com.microsoft.powerpoint.ppt",
              "com.adobe.photoshop- image", "com.microsoft.word.rtf", "com.microsoft.advanced- systems-format",
              "com.microsoft.advanced- stream-redirector"
            ],
            "isBase64": 0
          }
          iOSFileSelect.show(params, result => {
            let status = parseInt(result.status);
            // 状态200选取成功
            if (status == 200) {
              let url = result.url;
              uni.downloadFile({
                url: url,
                success: (res) => {
                  if (res.statusCode == 200) {
                    // filePath 可用于 uni.uploadFile 上传路径
                    let filePath = res.tempFilePath;
                    let name = filePath.split("/")[filePath.split("/").length - 1];
                    console.log(result);
                    const uploadTask = uni.uploadFile({
                      url: 'https://上传接口', //仅为示例,非真实的接口地址
                      filePath: filePath,
                      name: 'file',
                      formData: {
                        'user': 'test'
                      },
                      success: (uploadFileRes) => {
                        console.log(uploadFileRes.data);
                      }
                    });

                    uploadTask.onProgressUpdate((res) => {
                      console.log(res);
                      console.log('上传进度' + res.progress);
                      console.log('已经上传数据长度' + res.totalBytesSent);
                      console.log('预期需要上传数据长度' + res.totalBytesExpectedToSend);
                      // 测试条件取消上传任务。
                      if (res.progress > 1) {
                        uploadTask.abort();
                        let size = res.totalBytesExpectedToSend
                        let file = {
                          path: filePath,
                          name: name,
                          size: size,
                          type: 'file'
                        }
                        console.log(file); // File对象
                        // 可以在这里进行后续操作
                      }
                    });
                  }
                }
              });
            }
          });
      },


      // 安卓选择文件
      chooseFileAndroid() {
        /* eslint-disable */
        //调用原生文件系统管理器并选取文件获取文件地址
        var pickFile = {
          PickFile: function(callback,
            mimeTypes
          ) {
            /* 
              acceptType为你要查的文件类型"image/*","audio/*","video/*;image/*"  
              intent.setType("image/*");
              intent.setType("audio/*"); 
              选择音频 intent.setType("video/*;image/*"); 
              选择视频mp4 3gpandroid支持视频格式) 
            */
            var CODE_REQUEST = 1000;
            var main = plus.android.runtimeMainActivity();
            if (plus.os.name == 'Android') {
              var Intent = plus.android.importClass('android.content.Intent');
              var intent = new Intent(Intent.ACTION_GET_CONTENT);
              intent.addCategory(Intent.CATEGORY_OPENABLE);
              if (mimeTypes) {
                intent.setType("*/*");
                intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
              } else {
                intent.setType("*/*");
              }
              let _this = pickFile;
              main.onActivityResult = function(requestCode, resultCode, data) {
                if (requestCode == CODE_REQUEST) {
                  var uri = data.getData();
                  plus.android.importClass(uri);
                  var Build = plus.android.importClass('android.os.Build');
                  var isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

                  var DocumentsContract = plus.android.importClass('android.provider.DocumentsContract');
                  if (isKitKat &amp;&amp; DocumentsContract.isDocumentUri(main, uri)) {
                    console.log("版本大于 4.4");
                    if ("com.android.externalstorage.documents" == uri.getAuthority()) {
                      var docId = DocumentsContract.getDocumentId(uri);
                      var split = docId.split(":");
                      var type = split[0];

                      if ("primary" == type) {
                        var Environment = plus.android.importClass('android.os.Environment');
                        callback(Environment.getExternalStorageDirectory() + "/" + split[1]);
                      } else {
                        var System = plus.android.importClass('java.lang.System');
                        var sdPath = System.getenv("SECONDARY_STORAGE");
                        if (sdPath) {
                          callback(sdPath + "/" + split[1]);
                        }
                      }
                    } else if ("com.android.providers.downloads.documents" == uri.getAuthority()) {
                      var id = DocumentsContract.getDocumentId(uri);
                      var ContentUris = plus.android.importClass('android.content.ContentUris');
                      var contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), id);
                      callback(_this.getDataColumn(main, contentUri, null, null));
                    } else if ("com.android.providers.media.documents" == uri.getAuthority()) {
                      var docId = DocumentsContract.getDocumentId(uri);
                      var split = docId.split(":");
                      var type = split[0];

                      var MediaStore = plus.android.importClass('android.provider.MediaStore');
                      if ("image" == type) {
                        contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                      } else if ("video" == type) {
                        contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                      } else if ("audio" == type) {
                        contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                      } else {
                        contentUri = MediaStore.Files.getContentUri("external");
                      }
                      console.log("版本大于 4.4", type);
                      var selection = "_id=?";
                      var selectionArgs = new Array();
                      selectionArgs[0] = split[1];

                      callback(_this.getDataColumn(main, contentUri, selection, selectionArgs));
                    }
                  } else if ("content" == uri.getScheme()) {
                    callback(_this.getDataColumn(main, uri, null, null));
                  } else if ("file" == uri.getScheme()) {
                    callback(uri.getPath());
                  }
                }
              }
              main.startActivityForResult(intent, CODE_REQUEST);
            }
          },

          getDataColumn: function(main, uri, selection, selectionArgs) {
            plus.android.importClass(main.getContentResolver());
            let cursor = main.getContentResolver().query(uri, ['_data'], selection, selectionArgs, null);
            plus.android.importClass(cursor);
            console.log(cursor);
            if (cursor != null &amp;&amp; cursor.moveToFirst()) {
              var column_index = cursor.getColumnIndexOrThrow('_data');
              var result = cursor.getString(column_index)
              cursor.close();
              return result;
            }
            return null;
          }
        }
        /* eslint-disable no-new */
        // 拿到文件路径后,获取文件对象file
        pickFile.PickFile((path) => {
          //返回的路径 
          console.log(path);
          plus.io.resolveLocalFileSystemURL(path, (entry) => {

            entry.file((file) => {
              // file 对象即为所需的文件对象
              console.log("文件对象:", file);
              // 可以在这里进行后续操作
            }, (error) => {
              console.log("获取文件对象出现异常", error);
            });
          }, (error) => {
            console.log("解析本地文件路径出现异常", error);
          });
        }, '*/*')
      },
    }

原文地址:https://blog.csdn.net/weixin_44523517/article/details/131580335

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

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

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

发表回复

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