uni-app 希望可以开发一个app端非图像文件的选择上传组件

uni-app 希望可以开发一个app端非图像文件的选择上传组件

非图像文件选择上传组件开发需求

希望可以开发一个app端非图像文件的选择上传组件,并且不依赖原生插件

2 回复

使用h5

更多关于uni-app 希望可以开发一个app端非图像文件的选择上传组件的实战教程也可以访问 https://www.itying.com/category-93-b0.html


在uni-app中开发一个用于选择并上传非图像文件的组件,你可以利用uni-app提供的文件选择API来实现。以下是一个简单的示例代码,展示了如何创建一个文件选择上传组件。

首先,在你的uni-app项目中创建一个新的组件,比如命名为FileUploader.vue

<template>
  <view class="container">
    <button @click="chooseFile">选择文件</button>
    <view v-if="fileList.length">
      <view v-for="(file, index) in fileList" :key="index" class="file-item">
        <text>{{ file.name }}</text>
        <button @click="uploadFile(file)">上传</button>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      fileList: []
    };
  },
  methods: {
    chooseFile() {
      uni.chooseMessageFile({
        count: 9,
        type: 'file', // 仅允许选择文件,不包括图片
        success: (res) => {
          this.fileList = this.fileList.concat(res.tempFiles);
        },
        fail: (err) => {
          console.error('文件选择失败', err);
        }
      });
    },
    uploadFile(file) {
      uni.uploadFile({
        url: 'https://your-server-upload-url.com/upload', // 替换为你的服务器上传接口
        filePath: file.path,
        name: 'file',
        formData: {
          user: 'test'
        },
        success: (uploadFileRes) => {
          console.log('上传成功', uploadFileRes);
        },
        fail: (err) => {
          console.error('上传失败', err);
        }
      });
    }
  }
};
</script>

<style scoped>
.container {
  padding: 20px;
}
.file-item {
  margin-top: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>

代码说明:

  1. 模板部分

    • 一个按钮用于触发文件选择。
    • 一个循环用于显示已选择的文件列表,每个文件旁边有一个上传按钮。
  2. 脚本部分

    • chooseFile方法使用uni.chooseMessageFile API选择文件。注意type: 'file'参数限制只能选择文件,不包括图片。
    • uploadFile方法使用uni.uploadFile API上传文件到服务器。你需要替换url为你自己的服务器上传接口。
  3. 样式部分

    • 简单的样式布局,确保文件列表显示美观。

注意事项:

  • 确保你的服务器能够接收并处理文件上传请求。
  • 根据实际需要调整API参数和上传逻辑。
  • 此示例仅适用于选择非图像文件,如果需要支持图片和其他文件类型,可以调整uni.chooseMessageFiletype参数。
回到顶部