uniapp提供了uni.chooseImage(選擇圖片),?uni.chooseVideo(選擇視頻)這兩個api,但是對于打包成APP的話就沒有上傳文件的api了。因此我采用了plus.android中的方式來打開手機的文件管理從而上傳文件。
下面是我封裝的APP端選擇上傳圖片,視頻,文件的一個上傳組件。
<template><view class="upload-container"><u-icon name="plus" @click="showActionSheet" size="23"></u-icon><!-- <view class="upload-list"><view class="upload-item" v-for="(item, index) in fileList" :key="index"><image v-if="item.type === 'image'" class="preview-image" :src="item.url" mode="aspectFill"@click="previewFile(item)"></image><view v-else-if="item.type === 'video'" class="preview-video" @click="previewFile(item)"><image class="video-cover" :src="item.cover || item.url" mode="aspectFill"></image><view class="video-icon"><text class="iconfont icon-play"></text></view></view><view v-else class="preview-file" @click="previewFile(item)"><text class="iconfont icon-file"></text><text class="file-name">{{ item.name }}</text></view><text class="delete-icon" @click.stop="deleteFile(index)">×</text></view><view class="upload-button" v-if="fileList.length < maxCount"@click="showActionSheet"><text class="iconfont icon-add"></text><text class="upload-text">上傳{{ getUploadTypeText() }}</text></view></view> --><!-- <view class="upload-tips" v-if="tips">{{ tips }}</view> --></view>
</template><script>
export default {name: 'FileUploader',props: {// 上傳文件類型:all-所有類型, image-圖片, video-視頻, file-文件uploadType: {type: String,default: 'all'},// 標題title: {type: String,default: '文件上傳'},// 提示文字tips: {type: String,default: '支持jpg、png、mp4、doc、pdf等格式'},// 最大上傳數量maxCount: {type: Number,default: 9},// 初始文件列表value: {type: Array,default: () => []},// 圖片類型限制imageType: {type: Array,default: () => ['jpg', 'jpeg', 'png', 'gif']},// 視頻類型限制videoType: {type: Array,default: () => ['mp4', 'mov', 'avi']},// 文件類型限制fileType: {type: Array,default: () => ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'pdf', 'txt']},// 是否上傳到服務器uploadToServer: {type: Boolean,default: true},// 上傳接口地址uploadUrl: {type: String,default: ''}},data() {return {fileList: [],arrFile:[]}},created() {// 初始化文件列表if (this.value && this.value.length) {this.fileList = JSON.parse(JSON.stringify(this.value))}},watch: {value: {handler(newVal) {if (newVal && newVal.length) {this.fileList = JSON.parse(JSON.stringify(newVal))}},deep: true}},methods: {// 獲取上傳類型文本getUploadTypeText() {switch (this.uploadType) {case 'image':return '圖片'case 'video':return '視頻'case 'file':return '文件'default:return '文件'}},// 顯示操作菜單showActionSheet() {let itemList = []// if (this.uploadType === 'all' || this.uploadType === 'image') {// itemList.push('上傳圖片')// }// if (this.uploadType === 'all' || this.uploadType === 'video') {// itemList.push('上傳視頻')// }if (this.uploadType === 'all' || this.uploadType === 'file') {// 檢查平臺支持// #ifdef APP-PLUSconst appPlus = plus.os.name.toLowerCase();if (appPlus === 'android' || appPlus === 'ios') {itemList.push('上傳文件')}// #endif// #ifdef H5itemList.push('上傳文件')// #endif// #ifdef MP-WEIXINitemList.push('上傳文件')// #endif}uni.showActionSheet({itemList,success: res => {const index = res.tapIndexif (itemList[index] === '上傳圖片') {this.chooseImage()} else if (itemList[index] === '上傳視頻') {this.chooseVideo()} else if (itemList[index] === '上傳文件') {this.selectAndUploadFile()}}})},// 選擇圖片chooseImage() {uni.chooseImage({count: this.maxCount - this.fileList.length,sizeType: ['original', 'compressed'],sourceType: ['album', 'camera'],success: res => {const tempFiles = res.tempFiles// 檢查文件類型for (let i = 0; i < tempFiles.length; i++) {const file = tempFiles[i]const extension = this.getFileExtension(file.path)if (!this.imageType.includes(extension.toLowerCase())) {uni.showToast({title: `不支持${extension}格式的圖片`,icon: 'none'})continue}// 添加到文件列表const fileItem = {name: this.getFileName(file.path),url: file.path,size: file.size,type: 'image',extension: extension,status: 'ready' // ready, uploading, success, fail}this.fileList.push(fileItem)// 上傳到服務器if (this.uploadToServer) {this.uploadFileToServer(fileItem, this.fileList.length - 1)}}this.emitChange()}})},// 選擇視頻chooseVideo() {uni.chooseVideo({count: 1,sourceType: ['album', 'camera'],success: res => {const extension = this.getFileExtension(res.tempFilePath)if (!this.videoType.includes(extension.toLowerCase())) {uni.showToast({title: `不支持${extension}格式的視頻`,icon: 'none'})return}// 添加到文件列表const fileItem = {name: this.getFileName(res.tempFilePath),url: res.tempFilePath,cover: '', // 視頻封面,可以通過后端生成size: res.size,duration: res.duration,type: 'video',extension: extension,status: 'ready'}this.fileList.push(fileItem)// 上傳到服務器if (this.uploadToServer) {this.uploadFileToServer(fileItem, this.fileList.length - 1)}this.emitChange()}})},// 選擇并上傳文件函數selectAndUploadFile(){// 顯示加載提示uni.showLoading({title: '準備選擇文件',});// 選擇文件this.chooseFile().then(filePath => {// 選擇文件成功后上傳return this.uploadFile(filePath);}).then(result => {// 上傳成功的處理uni.hideLoading();uni.showToast({title: '上傳成功',icon: 'success'});console.log('上傳結果:', result);// 在此處理上傳成功后的業務邏輯}).catch(error => {// 錯誤處理uni.hideLoading();uni.showToast({title: error.message || '操作失敗',icon: 'none'});console.error('文件操作錯誤:', error);});},// 選擇文件方法chooseFile(){return new Promise((resolve, reject) => {try {// #ifdef APP-PLUSconst MediaStore = plus.android.importClass('android.provider.MediaStore');const main = plus.android.runtimeMainActivity();const Uri = plus.android.importClass('android.net.Uri');plus.io.chooseFile({title: '選擇文件',filetypes: ['xlsx', 'xls', 'pdf', 'doc', 'docx'], // 允許的文件類型multiple: false, // 是否允許多選}, (event) => {if (event.files && event.files.length > 0) {const tempFilePath = decodeURIComponent(event.files[0]);console.log('選擇的虛擬路徑:', tempFilePath);// 解析文件IDconst uri = MediaStore.Files.getContentUri("external");// 導入contentResolverplus.android.importClass(main.getContentResolver());// 從虛擬路徑中提取IDconst parts = tempFilePath.split(':');const fileId = parts[parts.length - 1];console.log('文件ID:', fileId);// 查詢真實路徑let cursor = main.getContentResolver().query(uri, ['_data'], "_id=?", [fileId], null);plus.android.importClass(cursor);let realPath = null;if (cursor != null && cursor.moveToFirst()) {const columnIndex = cursor.getColumnIndexOrThrow('_data');realPath = cursor.getString(columnIndex);cursor.close();}if (realPath) {// 轉換為file://格式const filePath = 'file://' + realPath;console.log('文件真實路徑:', filePath);resolve(filePath);} else {reject(new Error('無法獲取文件路徑'));}} else {reject(new Error('未選擇文件'));}}, (error) => {reject(new Error('選擇文件失敗: ' + error.message));});// #endif// #ifdef H5// H5環境下的文件選擇const input = document.createElement('input');input.type = 'file';input.accept = '.xlsx,.xls,.pdf,.doc,.docx';input.onchange = (e) => {const file = e.target.files[0];if (file) {resolve(file);} else {reject(new Error('未選擇文件'));}};input.click();// #endif// #ifdef MP-WEIXIN// 微信小程序環境wx.chooseMessageFile({count: 1,type: 'file',extension: ['xlsx', 'xls', 'pdf', 'doc', 'docx'],success: (res) => {if (res.tempFiles && res.tempFiles.length > 0) {resolve(res.tempFiles[0].path);} else {reject(new Error('未選擇文件'));}},fail: (err) => {reject(new Error('選擇文件失敗: ' + err.errMsg));}});// #endif// 其他平臺// #ifdef MP-ALIPAY || MP-BAIDU || MP-TOUTIAO || MP-QQreject(new Error('當前平臺不支持文件選擇'));// #endif} catch (e) {reject(new Error('選擇文件出錯: ' + e.message));}});},// 上傳文件方法uploadFile (filePath){return new Promise((resolve, reject) => {uni.showLoading({title: '上傳中...',mask: true});const token = uni.getStorageSync('token');if (!token) {reject(new Error('登錄狀態已失效,請重新登錄'));return;}// 準備表單數據const formData = {// 這里可以添加業務所需參數shangpinbianma: this.goodsDetail?.bianma || '',uploadTime: new Date().getTime()};console.log(filePath,'filepath')uni.uploadFile({url: '...', // 替換為您的服務器地址method: 'POST',name: 'file',filePath: filePath,formData: formData,header: {accept: "application/json",Authorization:"",},success: (res) => {console.log('上傳響應:', res);// 檢查登錄狀態if (res.statusCode === 200) {let result;try {// 解析返回結果if (typeof res.data === 'string') {result = JSON.parse(res.data);} else {result = res.data;}// 檢查登錄狀態if (result.code === '-110' || result.code === '-120' || result.code === '-130' || result.code === '-150') {console.log('登錄已失效');if (result.code !== '-120') {uni.showToast({title: '登錄已失效',icon: 'none'});}// 跳轉到登錄頁uni.reLaunch({url: '/pages/login/index'});reject(new Error('登錄已失效'));} else if (result.success) {//此處記得修改成為你的響應判斷// 上傳成功resolve(result);} else {// 其他業務錯誤reject(new Error(result.message || '上傳失敗'));}} catch (e) {reject(new Error('解析上傳結果失敗: ' + e.message));}} else {reject(new Error('上傳請求失敗,狀態碼: ' + res.statusCode));}},fail: (err) => {reject(new Error('上傳失敗: ' + (err.errMsg || JSON.stringify(err))));},complete: () => {uni.hideLoading();}});});},// 獲取文件擴展名getFileExtension(path) {if (!path) return ''return path.substring(path.lastIndexOf('.') + 1) || ''},// 獲取文件名getFileName(path) {if (!path) return ''return path.substring(path.lastIndexOf('/') + 1) || '未命名文件'},// 觸發變更事件emitChange() {this.$emit('input', this.fileList)this.$emit('change', this.fileList)}}
}
</script><style lang="scss">
.upload-container {width: 100%;padding: 20rpx;box-sizing: border-box;.upload-title {font-size: 30rpx;font-weight: bold;margin-bottom: 20rpx;}.upload-list {display: flex;flex-wrap: wrap;}.upload-item, .upload-button {position: relative;width: 200rpx;height: 200rpx;margin: 0 20rpx 20rpx 0;border-radius: 8rpx;overflow: hidden;box-sizing: border-box;}.upload-item {border: 1rpx solid #eee;.preview-image {width: 100%;height: 100%;}.preview-video {width: 100%;height: 100%;position: relative;.video-cover {width: 100%;height: 100%;}.video-icon {position: absolute;left: 50%;top: 50%;transform: translate(-50%, -50%);width: 60rpx;height: 60rpx;background-color: rgba(0, 0, 0, 0.5);border-radius: 50%;display: flex;align-items: center;justify-content: center;.icon-play {color: #fff;font-size: 30rpx;}}}.preview-file {width: 100%;height: 100%;display: flex;flex-direction: column;align-items: center;justify-content: center;background-color: #f7f7f7;.icon-file {font-size: 60rpx;color: #999;margin-bottom: 10rpx;}.file-name {font-size: 24rpx;color: #666;width: 90%;text-align: center;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;}}.delete-icon {position: absolute;right: 0;top: 0;width: 40rpx;height: 40rpx;background-color: rgba(0, 0, 0, 0.5);color: #fff;font-size: 30rpx;display: flex;align-items: center;justify-content: center;z-index: 10;}}.upload-button {border: 1rpx dashed #ddd;display: flex;flex-direction: column;align-items: center;justify-content: center;background-color: #f7f7f7;.icon-add {font-size: 60rpx;color: #999;margin-bottom: 10rpx;}.upload-text {font-size: 24rpx;color: #999;}}.upload-tips {font-size: 24rpx;color: #999;margin-top: 10rpx;}
}
</style>
改組件可以直接調用,希望可以幫助到大家。