html实现选择头像,HTML5实现上传头像图片大小选择(简单实现)

HTML5仿微博图片上传后大小选择,请使用chrom或者FireFox运行、如果报SECURITY_ERR需要把文件放在服务器端、比如nginx里。

1.[代码][HTML]代码

New Document

180×180

100×100

50×50

30×30

var photo={

"this":document.getElementById("photo"),

"context":document.getElementById("photo").getContext("2d"),

"width":document.getElementById("photo").width,

"height":document.getElementById("photo").height

};

var photos={

"bPhoto":{

"context":document.getElementById("bPhoto").getContext("2d"),

"width":document.getElementById("bPhoto").width,

"height":document.getElementById("bPhoto").height

},"mPhoto":{

"context":document.getElementById("mPhoto").getContext("2d"),

"width":document.getElementById("mPhoto").width,

"height":document.getElementById("mPhoto").height

},"sPhoto":{

"context":document.getElementById("sPhoto").getContext("2d"),

"width":document.getElementById("sPhoto").width,

"height":document.g

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,Web前端头像上传实现可以使用HTML5中的FormData对象和XMLHttpRequest对象来完成,具体步骤如下: 1.在HTML页面中,添加一个包含上传按钮的表单: ```html <form id="avatar-form"> <input type="file" id="avatar-input" name="avatar"> <button type="submit">上传</button> </form> ``` 2.在JavaScript中,获取表单元素和文件输入元素,并注册表单提交事件: ```javascript const form = document.querySelector('#avatar-form'); const input = document.querySelector('#avatar-input'); form.addEventListener('submit', (event) => { event.preventDefault(); // 阻止表单的默认提交行为 const formData = new FormData(); // 创建FormData对象 formData.append('avatar', input.files[0]); // 添加文件到formData中 uploadAvatar(formData); // 调用上传函数 }); ``` 3.定义上传函数,使用XMLHttpRequest发送POST请求: ```javascript function uploadAvatar(formData) { const xhr = new XMLHttpRequest(); xhr.open('POST', '/api/upload/avatar', true); xhr.setRequestHeader('Content-Type', 'multipart/form-data'); xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { console.log('上传成功'); } }; xhr.send(formData); } ``` 4.在后端服务器中,接收上传的文件并进行处理。例如使用Node.js的Express框架: ```javascript const express = require('express'); const multer = require('multer'); const app = express(); const upload = multer({ dest: 'uploads/' }); // 指定文件存储目录 app.post('/api/upload/avatar', upload.single('avatar'), (req, res) => { const file = req.file; // 获取上传的文件信息 // 处理上传的文件,并返回结果 res.json({ success: true }); }); app.listen(3000, () => { console.log('服务器已启动'); }); ``` 以上是一个简单的Web前端头像上传实现例子,需要注意的是,上传文件时应该注意文件大小的限制,以及后端服务器的安全配置。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值