uniapp uni.request 上传文件
时间: 2025-01-14 13:12:20 浏览: 133
### 文件上传功能实现
在 UniApp 开发环境中,`uni.request` 并不是最理想的文件上传工具;官方推荐使用 `uni.uploadFile` API 来完成这一任务[^1]。然而,在某些特定场景下,如果确实希望通过 `uni.request` 实现类似的文件上传逻辑,则可以考虑构建 FormData 对象并将其作为请求体的一部分传递给服务器。
下面是一个基于 `uni.request` 的模拟文件上传案例:
```javascript
// utils/request.js - 自定义封装的请求函数
export function uploadFile(filePath, fileType) {
const formData = new FormData();
formData.append('file', { uri: filePath, type: fileType });
return new Promise((resolve, reject) => {
uni.request({
url: '/api/upload',
method: 'POST',
data: formData,
header: {
'content-type': 'multipart/form-data'
},
success: res => resolve(res),
fail: err => reject(err)
});
});
}
```
请注意上述代码仅适用于支持 Fetch API 和 Blob 类型的对象环境。对于实际应用中的跨平台兼容性问题,建议优先采用 `uni.uploadFile()` 接口来处理文件传输需求[^3]。
#### 使用示例
假设有一个按钮用于触发图片选择器,并将选中的照片提交到服务器端保存:
```html
<!-- pages/index/index.vue -->
<template>
<view class="container">
<button @click="chooseImage">选择图片</button>
<!-- 显示已选取的照片缩略图 -->
<image v-if="localFilePath" :src="localFilePath"></image>
</view>
</template>
<script>
import {uploadFile} from '@/utils/request';
export default {
data() {
return {
localFilePath: ''
};
},
methods: {
async chooseImage() {
try {
let result = await uni.chooseImage({count: 1});
this.localFilePath = result.tempFiles[0].path;
// 调用自定义上传方法
await uploadFile(this.localFilePath, 'image/jpeg');
console.log('Upload succeeded!');
} catch(error){
console.error('Failed to select or upload image:', error);
}
}
}
};
</script>
```
此段代码展示了如何结合前端组件与后台服务交互的过程,实现了简单的图像挑选及上传流程[^2]。
阅读全文
相关推荐


















