返回文章列表
Bug解决方案
uniapp移动端文件处理base64

解决uniapp开发app无法使用uni.getFileSystemManager、chooseFile获取文件内容,导致无法处理文件内容

需求:我在使用uniapp开发手机app时有一个需求:需要可以让用户选择自己手机上的一个文件,然后app处理成base64编码,然后传递到后端。

问题:uniapp开发app无法使用uni.getFileSystemManager()、uni.chooseFile(),导致用户无法选择文件、app无法读取文件内容,uniapp官网建议这种情况下,使用5+api原生开发,但是这个方法十分复杂,实现起来很麻烦。然后我就尝试用AI帮我写代码,结果写了半天也没成功。

解决思路: 用过vue开发网页的人都知道,用vue开发浏览器网页想要读取文件、修改文件十分简单,那我们能不能在app中模拟一个类似网页的页面来进行读取、修改文件呢?毕竟在网页中读取、修改文件是十分简单的。 巧合的是uniapp还真有这个功能,可以使用web-view组件可以在页面中加入一个网页组件来,然后我们可以在网页组件中对文件进行处理。

我在静态资源中加入一个file-picker.html,然后在index.vue中添加这个网页组件,就能处理文件了(这个file-picker.html功能是选择文件,转为base64编码,并打印在控制台。读者可以根据自己实际需要修改,可以直接告诉AI你需要file-picker.html需要什么功能,直接让它帮忙快速修改)

//这个是index.vue文件
<template>
	<view class="content">
		<text class="title">首页</text>
		<web-view :src="webviewUrl" class="webview"></web-view>
	</view>
</template>
 
<script>
export default {
	data() {
		return {
			webviewUrl: '/static/file-picker.html'
		}
	}
}
</script>
 
<style>
.content {
	display: flex;
	flex-direction: column;
	align-items: center;
	padding: 20rpx;
}
.title {
	font-size: 36rpx;
	color: #333;
	margin-bottom: 20rpx;
}
.webview {
    width: 100%;
    height: 600rpx;
    border: 1px solid #ccc;
}
</style>
//这个是file-picker.html文件
<!DOCTYPE html>
<html>
 
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>文件选择</title>
  <style>
    body {
      margin: 20px;
      font-family: Arial;
    }
 
    .file-input {
      width: 100%;
      padding: 20px;
      border: 2px dashed #007aff;
      border-radius: 10px;
      text-align: center;
      cursor: pointer;
      background: #f8f9fa;
    }
 
    .file-input:active {
      background: #e9ecef;
    }
 
    .file-input input {
      display: none;
    }
 
    .file-label {
      color: #007aff;
      font-size: 16px;
      display: block;
      padding: 10px;
    }
  </style>
</head>
 
<body>
  <div class="file-input" onclick="triggerFileInput()">
    <label class="file-label">点击选择文件</label>
    <input type="file" id="fileInput" accept="*/*">
  </div>
 
  <script>
    function triggerFileInput() {
      document.getElementById('fileInput').click();
    }
 
    document.getElementById('fileInput').addEventListener('change', function (e) {
      const file = e.target.files[0];
      if (file) {
        console.log('选择的文件:', file.name, '大小:', file.size, '类型:', file.type);
 
        const reader = new FileReader();
        reader.onload = function (e) {
          const base64 = e.target.result;
          console.log('文件base64编码:', base64);
        };
        reader.readAsDataURL(file);
      }
    });
  </script>
</body>
 
</html>