ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
[TOC] ## 单文件 ``` // <input type="file" /> const formData = new FormData(); const fileField = document.querySelector('input[type="file"]'); formData.append('username', 'abc123'); formData.append('avatar', fileField.files[0]); fetch('https://example.com/profile/avatar', { method: 'PUT', body: formData }) .then(response => response.json()) .then(result => { console.log('Success:', result); }) .catch(error => { console.error('Error:', error); }); ``` ### 上传多个文件 ``` // <input type="file" multiple /> const formData = new FormData(); const photos = document.querySelector('input[type="file"][multiple]'); formData.append('title', 'My Vegas Vacation'); for (let i = 0; i < photos.files.length; i++) { formData.append(`photos_${i}`, photos.files[i]); } fetch('https://example.com/posts', { method: 'POST', body: formData, }) .then(response => response.json()) .then(result => { console.log('Success:', result); }) .catch(error => { console.error('Error:', error); }); ```