Cơ chế tải lên tập tin trên nền tảng Uni-App
Quá trình tải lên tập tin trong Uni-App vận hành dựa trên sự phối hợp giữa client và server. Phần giao diện sử dụng API uni.chooseMedia để người dùng chọn tài nguyên, sau đó truyền dữ liệu qua uni.uploadFile đến endpoint chỉ định. Bên phía máy chủ (thường là PHP/Node.js) sẽ xử lý việc lưu trữ, kiểm tra định dạng và phản hồi trạng thái.
Triển khai trên ứng dụng native
Trước khi phát triển, cần cấu hình quyền truy cập tập tin trong manifest.json và cài đặt các phụ thuộc cần thiết qua npm/yarn. Dưới đây là mẫu triển khai sử dụng Composition API:
<template>
<view class="upload-container">
<button @tap="triggerFileSelection">Chọn tài liệu</button>
<progress v-if="uploading" :percent="progress" />
</view>
</template>
<script setup>
import { ref } from 'vue';
const selectedDocument = ref(null);
const uploading = ref(false);
const progress = ref(0);
const triggerFileSelection = async () => {
const { tempFiles } = await uni.chooseMedia({
count: 1,
mediaType: ['file']
});
selectedDocument.value = tempFiles[0];
};
const submitDocument = async () => {
if (!selectedDocument.value) return;
uploading.value = true;
try {
const response = await uni.uploadFile({
url: 'https://api.example.com/upload',
filePath: selectedDocument.value.tempFilePath,
name: 'document',
header: { 'Content-Type': 'multipart/form-data' },
formData: {
userId: 'user_123',
timestamp: Date.now()
},
success: (res) => {
console.log('Upload thành công:', JSON.parse(res.data));
},
fail: (error) => {
uni.showToast({ title: 'Lỗi tải lên', icon: 'error' });
},
complete: () => {
uploading.value = false;
}
});
// Xử lý tiến trình
response.onProgressUpdate((status) => {
progress.value = status.progress;
});
} catch (e) {
console.error('Exception:', e);
}
};
</script>
Điều chỉnh cho mini-program
Các nền tảng mini-program (WeChat/Alipay) áp dụng giới hạn nghiêm ngặt về định dạng và kích thước tập tin. Cần xử lý khác biệt hệ điều hành thông qua:
const handleMiniProgramUpload = async (files) => {
for (const file of files) {
// Kiểm tra định dạng
if (!/\.jpg|\.png|\.pdf$/.test(file.name)) {
uni.showToast({ title: 'Định dạng không hợp lệ', icon: 'none' });
continue;
}
// Tối ưu hóa cho iOS/Android
const adjustedPath = uni.getEnv() === 'iOS'
? file.tempFilePath.replace('file://', '')
: file.tempFilePath;
await uni.uploadFile({
url: 'https://mini-api.example.com/v2/upload',
filePath: adjustedPath,
name: 'attachment',
success: ({ data }) => {
const result = JSON.parse(data);
if (result.code === 200) {
console.log('Tải lên thành công:', result.url);
}
}
});
}
};
Xử lý trên nền tảng Quick App
Quick App yêu cầu cấu hình đặc biệt cho quyền truy cập hệ thống tập tin. Mẫu code sau minh họa quy trình tải lên với cơ chế nén:
const quickAppUpload = async () => {
const { tempFiles } = await uni.chooseImage({
count: 3,
sizeType: ['compressed'] // Tự động nén ảnh
});
const uploadPromises = tempFiles.map(file =>
uni.uploadFile({
url: 'https://quickapp-api.example.com/upload',
filePath: file.path,
name: 'media',
formData: {
compression: 'high'
}
})
);
try {
const results = await Promise.all(uploadPromises);
results.forEach(res => {
if (res.statusCode === 201) {
uni.previewImage({ urls: [res.data] });
}
});
} catch (uploadError) {
uni.showModal({
title: 'Lỗi hệ thống',
content: 'Không kết nối được máy chủ'
});
}
};
Chiến lược tối ưu đa nền tảng
- Xử lý bất đồng bộ: Sử dụng Promise.all cho tải lên hàng loạt
- Nén dữ liệu: Áp dụng thư viện compress-image trước khi gửi
- Quản lý lỗi tập trung: Xây dựng lớp Error Handler chung
- Định chuẩn endpoint: Sử dụng biến môi trường cho các URL khác nhau
Các nền tảng áp dụng cơ chế xác thực khác nhau: Mini-program yêu cầu token session, ứng dụng native sử dụng certificate pinning, trong khi Quick App cần khai báo quyền trong config.xml. Việc kiểm tra runtime environment qua uni.getSystemInfoSync() giúp điều hướng logic phù hợp.