微信小程序uploadFile接口实现文件上传

微信小程序uploadFile接口实现文件上传
最新回答
幽兰黛尔

2026-10-23 06:01:03

上一节我们讨论了小程序的request请求,掌握了基本的网络请求方式。这节我们将通过使用小程序的uploadFile接口和后端php接口实现文件上传功能。通过学习这部分内容,你可以了解如何使用php实现上传接口,并结合前端实现一个完整的文件上传操作。

我们假设使用的是创建新项目的模板。在index.vue文件中,首先在最上方添加如下代码:

<template>
view style="width: 750rpx;height: 200rpx;display: flex;flex-direction: column;">
上传的文件名:
button type="primary" style="width: 500rpx;" @click="upload">点击上传</button>
/view
/template

通过点击按钮触发upload方法。接下来,我们需要选择文件并上传。我们先编写一个文件选择的代码:

<script>
export default {
data() {
return {
title: 'Hello'
}
},
onLoad() {
let that = this;
uni.chooseImage({
success: (chooseImageRes) => {
const tempFilePaths = chooseImageRes.tempFilePaths;
console.log(tempFilePaths);
}
});
},
methods: {
upload() {
let that = this;
console.log("我被点击了");
uni.chooseImage({
success: (chooseImageRes) => {
const tempFilePaths = chooseImageRes.tempFilePaths;
console.log(tempFilePaths);
uni.uploadFile({
url: 'https://你的接口/tp_imgsrc.php',
filePath: tempFilePaths[0],
name: 'file',
formData: {},
success: (uploadFileRes) => {
let json_data = JSON.parse(uploadFileRes.data);
console.log(json_data['errCode']);
if (json_data['errCode'] == 0) {
uni.showToast({
title: json_data['error_message'],
icon: 'none',
duration: 2000
});
} else {}
});
});
}}
});
}

在服务器上新建一个php文件作为上传接口,代码如下:

?php
function uploadimg() {
$file = $_FILES['file'];
if ($file) {
$ext = pathinfo($file['name'], PATHINFO_EXTENSION);
$target = 'upload/' . uniqid() . '.' . $ext;
if (!move_uploaded_file($file['tmp_name'], $target)) {
$GLOBALS['error_message'] = '上传图片失败';
echo $GLOBALS['error_message'];
}
die(json_encode(array('errCode' => 0, 'error_message' => '图片上传成功', 'file' => $target), 480));
}
}

最后,我们需要处理成功上传后的反馈信息:

<script>
export default {
data() {
return {
title: 'Hello'
}
},
onLoad() {
let that = this;
uni.chooseImage({
success: (chooseImageRes) => {
const tempFilePaths = chooseImageRes.tempFilePaths;
console.log(tempFilePaths);
uni.uploadFile({
url: 'https://你的接口/tp_imgsrc.php',
filePath: tempFilePaths[0],
name: 'file',
formData: {},
success: (uploadFileRes) => {
let json_data = JSON.parse(uploadFileRes.data);
console.log(json_data['errCode']);
if (json_data['errCode'] == 0) {
uni.showToast({
title: json_data['error_message'],
icon: 'none',
duration: 2000
});
}
});
});
}}
});
}

至此,通过使用uploadFile接口和php后端接口,我们已经实现了微信小程序的文件上传功能。