[Javascript] 文件上传
AJAX 就是指在web应用程序中异步向服务器发送请求。
它的实现方式有两种,XMLHttpRequest 简称XHR
和Fetch
以下是两者的对比
功能点 | XHR | Fetch |
---|---|---|
基本的请求能力 | ✅ | ✅ |
基本的获取响应能力 | ✅ | ✅ |
监控请求进度 | ✅ | ❌ |
监控响应进度 | ✅ | ✅ |
Service Worker中是否可用 | ❌ | ✅ |
控制cookie的携带 | ❌ | ✅ |
控制重定向 | ❌ | ✅ |
请求取消 | ✅ | ✅ |
自定义referrer | ❌ | ✅ |
流 | ❌ | ✅ |
API风格 | Event |
Promise |
活跃度 | 停止更新 | 不断更新 |
上传接口
请求路径:/upload/single
请求方法:POST
消息格式:multipart/form-data
字段名称:avatar
允许的后缀名:['.jpg', '.jpeg', '.bmp', '.webp', '.gif', '.png']
最大尺寸:1M
响应格式:JSON
响应结果示例:
// 成功
{
"data": "文件的访问地址"
}
// 失败:后缀名不符号要求
{
"errCode": 1,
"errMsg": "后缀名不符合要求"
}
// 失败:文件过大
{
"errCode": 2,
"errMsg": "文件过大"
}
Code:
const $ = document.querySelector.bind(document);
const doms = {
img: $('.preview'),
container: $('.upload'),
select: $('.upload-select'),
selectFile: $('.upload-select input'),
progress: $('.upload-progress'),
cancelBtn: $('.upload-progress button'),
delBtn: $('.upload-result button'),
};
function showArea(areaName) {
doms.container.className = `upload ${areaName}`;
}
function setProgress(value) {
doms.progress.style.setProperty('--percent', value);
}
doms.selectFile.onchange = (e) => {
const file = e.target.files[0];
// 显示预览图
const reader = new FileReader();
reader.onload = (e) => {
// 读取完成
doms.img.src = e.target.result;
showArea('progress');
upload(file);
};
reader.readAsDataURL(file); // 将文件数据读取为 DataURL(base64编码)
};
function upload(file) {
setProgress(0);
// XHR
const xhr = new XMLHttpRequest();
xhr.open('POST', 'http://myserver.com:9527/upload/single'); // 配置请求
xhr.upload.onprogress = (e) => {
const percent = Math.floor((e.loaded / e.total) * 100);
setProgress(percent);
};
xhr.onload = () => {
showArea('result');
};
// xhr.abort(); // 中止请求
const form = new FormData(); // 生成multipart/form-data格式的请求体
form.append('avatar', file);
xhr.send(form);
}
分类:
Javascript
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2024-02-09 [Go] A simple Go server
2021-02-09 [Bash] Chain Commands with Pipes and Redirect Output in Bash
2021-02-09 [Bash] Use Conditional Statements in Bash
2018-02-09 [ReactVR] Animate Text, Images, Views, and 3D Elements Using the Animated Library in React VR
2016-02-09 [Cycle.js] Fine-grained control over the DOM Source
2016-02-09 [Cycle.js] Making our toy DOM Driver more flexible
2016-02-09 [Redux] Generating Containers with connect() from React Redux (VisibleTodoList)