微信小程序文件上传通常包含五个步骤:选择本地文件、前端校验、调用 wx.uploadFile、服务端安全保存、把返回的文件信息写入业务表。只完成“选择文件”并不等于上传成功,生产项目还需要处理进度、取消、失败重试、预览、删除和权限校验。
一、常用文件选择接口
| 接口 | 用途 |
|---|---|
wx.chooseMedia | 从相册或相机选择图片、视频 |
wx.chooseMessageFile | 从微信会话中选择文档、压缩包等文件 |
wx.uploadFile | 以 multipart/form-data 上传单个本地临时文件 |
wx.downloadFile | 下载远程文件到本地临时路径 |
wx.openDocument | 打开 PDF、Word、Excel 等文档 |
图片和视频优先使用 wx.chooseMedia;微信聊天中的 PDF、Word 等附件使用 wx.chooseMessageFile。两者返回字段不同,应在工具层统一成相同文件对象。
二、上传流程设计
用户选择文件
↓
前端检查数量、扩展名、大小
↓
显示本地预览和待上传状态
↓
wx.uploadFile 上传到服务端
↓
服务端重新校验 MIME、大小、扩展名和权限
↓
随机命名并保存文件
↓
返回 file_id、url、name、size
↓
页面保存业务表单
前端校验只用于提升体验,任何前端参数都可以被绕过。文件安全最终必须由服务端负责。
三、配置合法域名
正式小程序上传前,需要在小程序管理后台配置 uploadFile 合法域名。生产地址必须使用 HTTPS,例如:
https://api.example.com
接口地址:
POST https://api.example.com/api/files/upload
不要把上传接口放在没有鉴权、没有限流的公共地址。开发工具可以临时关闭域名校验,但真机和正式版本仍受后台配置约束。
四、定义文件配置
// config/upload.js
export const UPLOAD_CONFIG = {
baseUrl: 'https://api.example.com',
uploadPath: '/api/files/upload',
maxCount: 6,
maxImageSize: 5 * 1024 * 1024,
maxDocumentSize: 10 * 1024 * 1024,
imageExtensions: ['jpg', 'jpeg', 'png', 'webp'],
documentExtensions: ['pdf', 'doc', 'docx', 'xls', 'xlsx'],
timeout: 60000
}
大小统一使用字节计算。业务页面可以在此基础上设置更严格限制,例如头像只允许一张且不超过 2 MB。
五、统一文件对象
// utils/file.js
export function getExtension(fileName = '') {
const index = fileName.lastIndexOf('.')
if (index <= 0 || index === fileName.length - 1) return ''
return fileName.slice(index + 1).toLowerCase()
}
export function createFileItem(file, type = 'file') {
const name = file.name || file.fileName || `file_${Date.now()}`
return {
localId: `${Date.now()}_${Math.random().toString(36).slice(2)}`,
name,
extension: getExtension(name),
size: Number(file.size || 0),
type: file.fileType || type,
tempFilePath: file.tempFilePath || file.path,
thumbTempFilePath: file.thumbTempFilePath || '',
status: 'pending',
progress: 0,
errorMessage: '',
fileId: '',
url: '',
uploadTask: null
}
}
localId 用于列表渲染和更新进度,不能使用数组 index 作为长期唯一标识,因为删除或重新排序后 index 会变化。
六、文件大小格式化
export function formatFileSize(bytes) {
const size = Number(bytes || 0)
if (size < 1024) return `${size} B`
if (size < 1024 * 1024) return `${(size / 1024).toFixed(1)} KB`
if (size < 1024 * 1024 * 1024) {
return `${(size / 1024 / 1024).toFixed(1)} MB`
}
return `${(size / 1024 / 1024 / 1024).toFixed(1)} GB`
}
七、前端文件校验
import { UPLOAD_CONFIG } from '../config/upload'
import { getExtension } from './file'
export function validateFile(file, options = {}) {
const {
extensions = UPLOAD_CONFIG.documentExtensions,
maxSize = UPLOAD_CONFIG.maxDocumentSize
} = options
if (!file.tempFilePath) {
return { valid: false, message: '未读取到文件路径' }
}
const extension = getExtension(file.name)
if (!extension || !extensions.includes(extension)) {
return {
valid: false,
message: `仅支持 ${extensions.join('、')} 格式`
}
}
if (!file.size || file.size <= 0) {
return { valid: false, message: '文件内容为空' }
}
if (file.size > maxSize) {
return {
valid: false,
message: `文件不能超过 ${(maxSize / 1024 / 1024).toFixed(0)} MB`
}
}
return { valid: true, message: '' }
}
扩展名只能作为初步判断,恶意文件可以伪造后缀。服务端必须使用真实 MIME 检测并限制可执行内容。
八、选择图片
import { createFileItem } from '../../utils/file'
import { validateFile } from '../../utils/upload'
import { UPLOAD_CONFIG } from '../../config/upload'
async chooseImages() {
const remain = UPLOAD_CONFIG.maxCount - this.data.files.length
if (remain <= 0) {
wx.showToast({ title: `最多上传 ${UPLOAD_CONFIG.maxCount} 个文件`, icon: 'none' })
return
}
try {
const result = await wx.chooseMedia({
count: remain,
mediaType: ['image'],
sourceType: ['album', 'camera'],
sizeType: ['compressed']
})
const accepted = []
for (const rawFile of result.tempFiles) {
const file = createFileItem(rawFile, 'image')
// chooseMedia 不一定返回原始文件名,图片按类型校验大小
const validation = validateFile(
{ ...file, name: file.name || 'image.jpg' },
{
extensions: UPLOAD_CONFIG.imageExtensions,
maxSize: UPLOAD_CONFIG.maxImageSize
}
)
if (!validation.valid) {
wx.showToast({ title: validation.message, icon: 'none' })
continue
}
accepted.push(file)
}
this.setData({ files: [...this.data.files, ...accepted] })
} catch (err) {
if (!String(err.errMsg || '').includes('cancel')) {
wx.showToast({ title: '选择图片失败', icon: 'none' })
}
}
}
九、选择会话文件
async chooseDocuments() {
const remain = UPLOAD_CONFIG.maxCount - this.data.files.length
if (remain <= 0) {
wx.showToast({ title: '已达到文件数量上限', icon: 'none' })
return
}
try {
const result = await wx.chooseMessageFile({
count: remain,
type: 'file',
extension: UPLOAD_CONFIG.documentExtensions
})
const accepted = []
for (const rawFile of result.tempFiles) {
const file = createFileItem(rawFile, 'file')
const validation = validateFile(file, {
extensions: UPLOAD_CONFIG.documentExtensions,
maxSize: UPLOAD_CONFIG.maxDocumentSize
})
if (!validation.valid) {
wx.showToast({ title: validation.message, icon: 'none' })
continue
}
accepted.push(file)
}
this.setData({ files: [...this.data.files, ...accepted] })
} catch (err) {
if (!String(err.errMsg || '').includes('cancel')) {
wx.showToast({ title: '选择文件失败', icon: 'none' })
}
}
}
十、封装 wx.uploadFile
// utils/upload.js
import { UPLOAD_CONFIG } from '../config/upload'
export function uploadFile(file, options = {}) {
const token = wx.getStorageSync('access_token') || ''
let uploadTask = null
const promise = new Promise((resolve, reject) => {
uploadTask = wx.uploadFile({
url: `${UPLOAD_CONFIG.baseUrl}${UPLOAD_CONFIG.uploadPath}`,
filePath: file.tempFilePath,
name: 'file',
header: {
Authorization: token ? `Bearer ${token}` : ''
},
formData: {
scene: options.scene || 'common',
business_id: String(options.businessId || '')
},
timeout: options.timeout || UPLOAD_CONFIG.timeout,
success(res) {
// wx.uploadFile 的 res.data 通常是字符串,需要手动解析
let body
try {
body = typeof res.data === 'string'
? JSON.parse(res.data)
: res.data
} catch (e) {
reject(new Error('服务器返回格式不正确'))
return
}
if (res.statusCode < 200 || res.statusCode >= 300) {
reject(new Error(body.message || `上传失败(${res.statusCode})`))
return
}
if (!body || body.code !== 0 || !body.data) {
reject(new Error((body && body.message) || '上传失败'))
return
}
resolve(body.data)
},
fail(err) {
const cancelled = String(err.errMsg || '').includes('abort')
reject(new Error(cancelled ? '上传已取消' : '网络异常,上传失败'))
}
})
if (typeof options.onProgress === 'function') {
uploadTask.onProgressUpdate(progress => {
options.onProgress(progress.progress)
})
}
})
return {
promise,
getTask: () => uploadTask,
abort: () => uploadTask && uploadTask.abort()
}
}
不要手动设置 multipart/form-data 的 Content-Type 边界,wx.uploadFile 会自动生成。手动覆盖可能导致服务端无法解析文件。
十一、页面上传单个文件
import { uploadFile } from '../../utils/upload'
uploadOne(localId) {
const index = this.data.files.findIndex(item => item.localId === localId)
if (index < 0) return Promise.reject(new Error('文件不存在'))
const file = this.data.files[index]
if (file.status === 'uploading' || file.status === 'success') {
return Promise.resolve(file)
}
this.setData({
[`files[${index}].status`]: 'uploading',
[`files[${index}].progress`]: 0,
[`files[${index}].errorMessage`]: ''
})
const uploader = uploadFile(file, {
scene: 'seal_application',
onProgress: progress => {
const currentIndex = this.data.files.findIndex(
item => item.localId === localId
)
if (currentIndex >= 0) {
this.setData({ [`files[${currentIndex}].progress`]: progress })
}
}
})
this.setData({ [`files[${index}].uploadTask`]: uploader })
return uploader.promise
.then(result => {
const currentIndex = this.data.files.findIndex(
item => item.localId === localId
)
if (currentIndex >= 0) {
this.setData({
[`files[${currentIndex}].status`]: 'success',
[`files[${currentIndex}].progress`]: 100,
[`files[${currentIndex}].fileId`]: result.file_id,
[`files[${currentIndex}].url`]: result.url,
[`files[${currentIndex}].uploadTask`]: null
})
}
return result
})
.catch(err => {
const currentIndex = this.data.files.findIndex(
item => item.localId === localId
)
if (currentIndex >= 0) {
this.setData({
[`files[${currentIndex}].status`]: 'failed',
[`files[${currentIndex}].errorMessage`]: err.message,
[`files[${currentIndex}].uploadTask`]: null
})
}
throw err
})
}
十二、批量上传
文件数量不多时可以顺序上传,逻辑简单,也不会瞬间占满网络连接:
async uploadAll() {
const pendingFiles = this.data.files.filter(item => {
return item.status === 'pending' || item.status === 'failed'
})
if (!pendingFiles.length) {
wx.showToast({ title: '没有待上传文件', icon: 'none' })
return
}
this.setData({ uploadingAll: true })
let successCount = 0
try {
for (const file of pendingFiles) {
try {
await this.uploadOne(file.localId)
successCount += 1
} catch (e) {
// 单个失败不阻断其他文件上传
}
}
const failedCount = pendingFiles.length - successCount
wx.showToast({
title: failedCount
? `成功 ${successCount} 个,失败 ${failedCount} 个`
: '上传完成',
icon: failedCount ? 'none' : 'success'
})
} finally {
this.setData({ uploadingAll: false })
}
}
大量文件需要限制并发数,例如同时上传 2~3 个。直接 Promise.all 上传过多文件可能造成网络拥塞和失败率上升。
十三、取消与重试上传
cancelUpload(e) {
const localId = e.currentTarget.dataset.id
const index = this.data.files.findIndex(item => item.localId === localId)
if (index < 0) return
const uploader = this.data.files[index].uploadTask
if (uploader && typeof uploader.abort === 'function') {
uploader.abort()
}
}
retryUpload(e) {
const localId = e.currentTarget.dataset.id
this.uploadOne(localId).catch(err => {
wx.showToast({ title: err.message, icon: 'none' })
})
}
十四、文件列表 WXML
<view class="upload-panel">
<view class="upload-actions">
<button size="mini" bindtap="chooseImages">选择图片</button>
<button size="mini" bindtap="chooseDocuments">选择文档</button>
</view>
<view class="file-list">
<view
class="file-item"
wx:for="{{files}}"
wx:key="localId"
>
<image
wx:if="{{item.type === 'image'}}"
class="file-thumb"
src="{{item.tempFilePath || item.url}}"
mode="aspectFill"
data-index="{{index}}"
bindtap="previewImage"
/>
<view wx:else class="file-icon">FILE</view>
<view class="file-main">
<view class="file-name">{{item.name}}</view>
<view class="file-meta">{{item.sizeText}}</view>
<progress
wx:if="{{item.status === 'uploading'}}"
percent="{{item.progress}}"
stroke-width="3"
active
/>
<view wx:if="{{item.status === 'failed'}}" class="file-error">
{{item.errorMessage}}
</view>
</view>
<button
wx:if="{{item.status === 'failed'}}"
size="mini"
data-id="{{item.localId}}"
bindtap="retryUpload"
>重试</button>
<button
wx:if="{{item.status === 'uploading'}}"
size="mini"
data-id="{{item.localId}}"
bindtap="cancelUpload"
>取消</button>
<text
class="file-delete"
data-id="{{item.localId}}"
bindtap="removeFile"
>删除</text>
</view>
</view>
<button
type="primary"
loading="{{uploadingAll}}"
disabled="{{uploadingAll || !files.length}}"
bindtap="uploadAll"
>上传全部</button>
</view>
十五、文件列表 WXSS
.upload-panel {
padding: 24rpx;
border-radius: 20rpx;
background: #fff;
}
.upload-actions {
display: flex;
gap: 20rpx;
margin-bottom: 24rpx;
}
.file-item {
display: flex;
align-items: center;
gap: 20rpx;
padding: 22rpx 0;
border-bottom: 1rpx solid #eef0f3;
}
.file-thumb,
.file-icon {
width: 96rpx;
height: 96rpx;
border-radius: 12rpx;
background: #f2f3f5;
}
.file-icon {
display: flex;
align-items: center;
justify-content: center;
color: #86909c;
font-size: 22rpx;
}
.file-main {
flex: 1;
min-width: 0;
}
.file-name {
overflow: hidden;
color: #1d2129;
font-size: 28rpx;
text-overflow: ellipsis;
white-space: nowrap;
}
.file-meta {
margin: 8rpx 0;
color: #86909c;
font-size: 22rpx;
}
.file-error {
color: #f53f3f;
font-size: 22rpx;
}
.file-delete {
color: #f53f3f;
font-size: 24rpx;
}
十六、预览图片
previewImage(e) {
const currentIndex = Number(e.currentTarget.dataset.index)
const imageFiles = this.data.files.filter(item => item.type === 'image')
const urls = imageFiles
.map(item => item.url || item.tempFilePath)
.filter(Boolean)
const currentFile = this.data.files[currentIndex]
const current = currentFile.url || currentFile.tempFilePath
if (current && urls.length) {
wx.previewImage({ current, urls })
}
}
如果列表同时包含图片和文档,页面 index 与过滤后的图片 index 可能不同。更稳妥的做法是通过 localId 查找当前文件,而不是直接复用数组下标。
十七、打开文档
openDocument(e) {
const localId = e.currentTarget.dataset.id
const file = this.data.files.find(item => item.localId === localId)
if (!file) return
if (file.tempFilePath) {
wx.openDocument({
filePath: file.tempFilePath,
showMenu: true,
fail() {
wx.showToast({ title: '暂不支持预览该文件', icon: 'none' })
}
})
return
}
wx.downloadFile({
url: file.url,
success(res) {
if (res.statusCode === 200) {
wx.openDocument({ filePath: res.tempFilePath, showMenu: true })
}
}
})
}
十八、删除文件
未上传文件只需从页面列表移除;已经上传的文件还要通知服务端删除或解除业务关联。
async removeFile(e) {
const localId = e.currentTarget.dataset.id
const index = this.data.files.findIndex(item => item.localId === localId)
if (index < 0) return
const file = this.data.files[index]
if (file.status === 'uploading' && file.uploadTask) {
file.uploadTask.abort()
}
if (file.fileId) {
const confirmed = await this.confirmDelete()
if (!confirmed) return
await request(`/api/files/${file.fileId}`, 'DELETE')
}
const files = this.data.files.filter(item => item.localId !== localId)
this.setData({ files })
}
服务端删除接口必须验证当前用户是否拥有该文件。不要只根据客户端传入的 file_id 直接删除磁盘文件。
十九、ThinkPHP 5.1 上传接口
// application/api/controller/File.php
namespace app\api\controller;
use think\Controller;
use think\Db;
class File extends Controller
{
public function upload()
{
$userId = $this->currentUserId();
$file = request()->file('file');
if (!$file) {
return json(['code' => 40001, 'message' => '请选择文件'], 400);
}
$scene = input('post.scene/s', 'common');
$rules = $this->getSceneRules($scene);
// ThinkPHP validate 先限制大小和扩展名
$checked = $file->validate([
'size' => $rules['max_size'],
'ext' => implode(',', $rules['extensions']),
]);
if (!$checked) {
return json([
'code' => 40002,
'message' => $file->getError(),
], 422);
}
// 使用 Fileinfo 检查真实 MIME,不能只相信后缀和客户端 Content-Type
$mime = $this->detectMime($file->getRealPath());
if (!in_array($mime, $rules['mimes'], true)) {
return json([
'code' => 40003,
'message' => '文件类型不允许',
], 422);
}
$saveRoot = ROOT_PATH . 'storage' . DS . 'uploads';
$info = $file->move($saveRoot);
if (!$info) {
return json([
'code' => 50001,
'message' => '文件保存失败',
], 500);
}
$relativePath = str_replace('\\', '/', $info->getSaveName());
$fileId = Db::name('file')->insertGetId([
'user_id' => $userId,
'scene' => $scene,
'original_name' => mb_substr($file->getInfo('name'), 0, 255),
'storage_path' => $relativePath,
'mime' => $mime,
'extension' => strtolower($info->getExtension()),
'size' => $info->getSize(),
'sha256' => hash_file('sha256', $info->getPathname()),
'status' => 1,
'create_time' => time(),
]);
return json([
'code' => 0,
'message' => '上传成功',
'data' => [
'file_id' => $fileId,
'name' => $file->getInfo('name'),
'size' => $info->getSize(),
'mime' => $mime,
'url' => url('api/file/download', ['id' => $fileId], true, true),
],
]);
}
private function detectMime($path)
{
$finfo = new \finfo(FILEINFO_MIME_TYPE);
return $finfo->file($path) ?: 'application/octet-stream';
}
private function getSceneRules($scene)
{
$rules = [
'image' => [
'max_size' => 5 * 1024 * 1024,
'extensions' => ['jpg', 'jpeg', 'png', 'webp'],
'mimes' => ['image/jpeg', 'image/png', 'image/webp'],
],
'document' => [
'max_size' => 10 * 1024 * 1024,
'extensions' => ['pdf', 'doc', 'docx', 'xls', 'xlsx'],
'mimes' => [
'application/pdf',
'application/msword',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.ms-excel',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
],
],
];
return $rules[$scene] ?? $rules['document'];
}
}
二十、文件记录表
CREATE TABLE admin_file (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
user_id BIGINT UNSIGNED NOT NULL,
scene VARCHAR(32) NOT NULL DEFAULT 'common',
original_name VARCHAR(255) NOT NULL,
storage_path VARCHAR(500) NOT NULL,
mime VARCHAR(120) NOT NULL,
extension VARCHAR(20) NOT NULL,
size BIGINT UNSIGNED NOT NULL,
sha256 CHAR(64) NOT NULL,
status TINYINT UNSIGNED NOT NULL DEFAULT 1,
create_time INT UNSIGNED NOT NULL,
delete_time INT UNSIGNED NOT NULL DEFAULT 0,
PRIMARY KEY (id),
KEY idx_user_created (user_id, create_time),
KEY idx_sha256 (sha256),
KEY idx_scene_status (scene, status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
数据库保存的是相对存储路径,不保存服务器绝对路径。下载和删除都通过 file_id 查询,并验证用户权限。
二十一、服务端删除接口
public function delete($id)
{
$userId = $this->currentUserId();
Db::startTrans();
try {
$file = Db::name('file')
->where('id', (int) $id)
->where('user_id', $userId)
->where('status', 1)
->lock(true)
->find();
if (!$file) {
Db::rollback();
return json(['code' => 40401, 'message' => '文件不存在'], 404);
}
// 如果文件已绑定正式业务单据,可改为解除关联或拒绝删除
Db::name('file')->where('id', $file['id'])->update([
'status' => 0,
'delete_time' => time(),
]);
Db::commit();
// 先软删除记录,物理文件由异步清理任务删除,便于失败重试
return json(['code' => 0, 'message' => '删除成功', 'data' => null]);
} catch (\Throwable $e) {
Db::rollback();
return json(['code' => 50001, 'message' => '删除失败'], 500);
}
}
二十二、Nginx 上传大小限制
server {
client_max_body_size 12m;
client_body_timeout 60s;
}
PHP 也需要配置:
upload_max_filesize = 10M
post_max_size = 12M
max_file_uploads = 10
max_execution_time = 60
Nginx、PHP 和业务代码的限制应保持一致,并给 multipart 表单留出少量额外空间。修改 php.ini 后需要重载 PHP-FPM。
二十三、文件存储安全
- 不要信任客户端文件名、扩展名和 Content-Type。
- 使用 Fileinfo 检测 MIME,并根据业务白名单判断。
- 使用随机文件名,原始文件名只用于展示。
- 文档和私有图片尽量存到 public 目录之外。
- 下载通过鉴权接口输出,不直接暴露真实磁盘路径。
- 禁止上传 PHP、脚本、HTML 等可执行内容。
- 高风险文档接入病毒扫描和内容安全检测。
- 设置用户级上传频率、文件数和总空间限额。
- 日志记录 file_id、用户、大小和结果,但避免记录敏感内容。
二十四、对象存储方案
文件量较大时,可以使用 OSS、COS 等对象存储。常见方案有:
- 小程序上传到业务服务器,再由服务器转存对象存储;
- 服务端生成临时上传凭证,小程序直传对象存储;
- 上传完成后,小程序通知业务服务端登记文件记录。
直传能降低业务服务器带宽压力,但临时凭证必须限制路径、文件类型、大小和有效期,不能把永久 AccessKey 放进小程序。
二十五、常见问题
1. 开发工具能上传,真机提示域名不合法
检查小程序后台的 uploadFile 合法域名、HTTPS 证书、域名备案和接口端口。开发工具关闭校验不能代替正式配置。
2. 服务端收不到文件
确认 wx.uploadFile 的 name 与后端 request()->file('file') 一致,不要手动设置错误的 multipart Content-Type。
3. 返回数据无法读取 code
wx.uploadFile 返回的 res.data 通常是字符串,需要先 JSON.parse,并捕获解析异常。
4. 上传到一半一直卡住
检查网络、服务端超时、Nginx client_max_body_size、PHP 上传限制和磁盘空间,并为上传设置超时和取消按钮。
5. 图片已上传但预览失败
检查返回 URL 是否为 HTTPS、是否需要鉴权、downloadFile 合法域名以及服务器 Content-Type。私有文件应通过临时签名 URL 或鉴权下载接口预览。
6. 选择文件返回 cancel 也弹错误
用户主动取消属于正常操作,应检查 errMsg 是否包含 cancel,不显示失败提示。
7. 删除页面记录后磁盘文件仍存在
页面删除只是前端状态变化。已上传文件需要调用服务端删除接口,并通过异步任务处理物理文件清理。
二十六、测试清单
- 测试允许与不允许的扩展名。
- 测试空文件、超大文件和伪造扩展名。
- 测试上传中断网、切后台、取消和重试。
- 测试同时选择多个文件和达到数量上限。
- 测试 Token 失效和用户越权删除。
- 测试 Nginx、PHP、应用三层大小限制。
- 测试同名文件不会互相覆盖。
- 测试服务端返回非 JSON 和 500 错误。
- 测试图片预览、文档打开和私有下载。
- 测试软删除与异步物理清理。
二十七、总结
微信小程序文件上传不只是调用一次 wx.uploadFile。完整实现需要统一选择结果、前后端双重校验、显示进度、支持取消和重试,并在服务端完成鉴权、MIME 检测、随机命名和安全存储。文件量增大后,再将存储层替换为带临时凭证的对象存储,页面和业务接口仍可保持一致。