Shaw0xyz 发表于 2024-6-26 12:34:49

uni-app uni-file-picker文件上传实现拍摄从相册选择获取图片上传文档服务器

本帖最后由 Shaw0xyz 于 2024-7-3 18:37 编辑

1. 引言

在移动和Web应用开发中,文件上传是一个常见功能。uni-app作为一款跨平台框架,提供了uni-file-picker组件,方便开发者实现文件上传功能。本文将详细介绍如何使用uni-file-picker组件,在H5和微信小程序中实现拍摄、从相册选择图片并上传到服务器的功能。

1.1 目标

通过本文,你将学会如何在uni-app中使用uni-file-picker组件,获取图片并上传到服务器。我们将分别介绍在H5和微信小程序中的实现方法。

2. 基本配置

在开始开发之前,确保你的项目已正确安装和配置uni-app。

2.1 安装uni-file-picker组件

在项目根目录下,使用以下命令安装uni-file-picker组件:

npm install @dcloudio/uni-ui --save

然后在main.js中引入uni-ui:

import Vue from 'vue'
import * as uni from '@dcloudio/uni-ui'

for (const key in uni) {
Vue.component(key, uni)
}

3. 实现文件上传功能

3.1 H5平台

在H5平台上,我们将实现拍摄和从相册选择图片,并将其上传到服务器。

3.1.1 使用uni-file-picker组件

在你的页面中添加uni-file-picker组件:

<template>
<view>
    <uni-file-picker @change="onFileChange" :fileMediatype="['image']" :sizeType="['original', 'compressed']"></uni-file-picker>
</view>
</template>

<script>
export default {
methods: {
    onFileChange(event) {
      const file = event.tempFiles;
      this.uploadFile(file);
    },
    uploadFile(file) {
      const formData = new FormData();
      formData.append('file', file);

      fetch('https://your-server-url/upload', {
      method: 'POST',
      body: formData,
      })
      .then(response => response.json())
      .then(data => {
      console.log('File uploaded successfully', data);
      })
      .catch(error => {
      console.error('Error uploading file', error);
      });
    }
}
}
</script>

在以上代码中,uni-file-picker组件用于选择图片文件,onFileChange方法处理文件选择事件,并调用uploadFile方法将文件上传到服务器。

3.2 微信小程序平台

在微信小程序平台上,我们也可以使用相同的组件和方法。

3.2.1 使用uni-file-picker组件

<template>
<view>
    <uni-file-picker @change="onFileChange" :fileMediatype="['image']" :sizeType="['original', 'compressed']"></uni-file-picker>
</view>
</template>

<script>
export default {
methods: {
    onFileChange(event) {
      const file = event.tempFiles;
      this.uploadFile(file);
    },
    uploadFile(file) {
      wx.uploadFile({
      url: 'https://your-server-url/upload',
      filePath: file.path,
      name: 'file',
      success(res) {
          const data = JSON.parse(res.data);
          console.log('File uploaded successfully', data);
      },
      fail(error) {
          console.error('Error uploading file', error);
      }
      });
    }
}
}
</script>

在以上代码中,onFileChange方法处理文件选择事件,并调用wx.uploadFile方法将文件上传到服务器。

4. 处理上传结果

无论是在H5还是微信小程序中,成功上传文件后都需要处理服务器返回的结果。可以在上传成功的回调中处理响应数据,例如显示上传成功的消息或保存返回的文件URL。

5. 结论

通过本文的介绍,我们详细讲解了如何使用uni-file-picker组件在uni-app中实现文件上传功能,包括拍摄和从相册选择图片,并将其上传到服务器。我们分别介绍了在H5和微信小程序平台上的实现方法。希望这篇文章能帮助你更好地理解和实现uni-app中的文件上传功能。如果在实现过程中遇到问题,建议参考uni-app官方文档或社区资源,进一步了解和解决相关问题。






/ 荔枝学姐de课后专栏 /

Hi!这里是荔枝学姐~

欢迎来到我的课后专栏

自然语言学渣 NLP摆烂姐

热衷于技术写作 IT边角料

AIGC & Coding & Linux ...

~互撩~ TG: @Shaw_0xyz
页: [1]
查看完整版本: uni-app uni-file-picker文件上传实现拍摄从相册选择获取图片上传文档服务器