uni-app 内置了文件上传的方法,但并不适用于阿里云对象存储方式,实践了很多种方式,最终还是选择了 web-view 配合 H5 实现文件上传。
具体使用用法如下:
- 必须 将 H5 页面放置在 src/hybrid/html 文件夹中
- 配置 web-view,使用@message 接收 web-view 传参
<template>
<view id="project-upload-file">
<web-view src="/hybrid/html/index.html" @message="handleMessage" />
</view>
</template>
<script lang="ts">
import { Component, Emit, Inject, Model, Prop, Provide, Vue, Watch, Mixins } from 'vue-property-decorator';
import { State, Getter, Action, Mutation, namespace } from 'vuex-class';
@Component
export default class ProjectUploadFile extends Vue {
// methods
public handleMessage(data: any): void {
console.log('返回数据:', data);
uni.navigateBack({ delta: 1 });
}
}
</script>
<style scoped lang="scss"></style>
- H5 页面使用原生 input 实现文件上传
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" />
<title>文件上传</title>
<style>
.upload-box {
display: flex;
flex-direction: column;
align-items: center;
}
#upload {
color: rgb(255, 255, 255);
background-color: rgb(41, 121, 255);
width: 100%;
margin-top: 10px;
font-size: 15px;
height: 40px;
border: 1px solid rgb(41, 121, 255);
border-radius: 5px;
}
</style>
</head>
<body>
<div class="upload-box">
<input type="file" id="file" style="display: none;" />
<button id="upload">选择文件</button>
</div>
<script type="text/javascript" src="https://js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.1.5.2.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/ali-oss/6.9.1/aliyun-oss-sdk.js"></script>
<script>
const client = new OSS({
accessKeyId: '****', // 你创建的Bucket时获取的
accessKeySecret: '****', // 你创建的Bucket时获取的
bucket: '****', // 你创建的Bucket名称
region: '****', // 你所购买oss服务的区域,默认oss-cn-hangzhou
endpoint: '****',
});
document.addEventListener('UniAppJSBridgeReady', function() {
// uni.postMessage({
// data: {
// action: 'message',
// },
// });
uni.getEnv(function(res) {
console.log('当前环境:' + JSON.stringify(res));
});
// 选择文件
const Upload = document.getElementById('upload');
Upload.onclick = () => {
oFile.click();
};
// 监听文件上传
const oFile = document.getElementById('file');
oFile.onchange = async () => {
const res = await client.put(oFile.files[0].name, oFile.files[0])
const data = {
filename: oFile.files[0].name.split('.')[0],
oss_filename: res.name,
oss_path: res.url,
};
uni.postMessage({
data: {
action: data,
},
});
// uni.navigateBack({
// delta: 1,
// });
};
});
</script>
</body>
</html>