返回 1. 创建
1. 创建
前端上传文件与缩略图
前端
2023-11-28 04:31:56
通常情况下,前端提交给服务器的数据格式为JSON格式,但很多时候用户想上传自己的头像、视频等,这些非文本数据的时候,就不能直接以JSON格式上传到后端了。需要使用FormData对象对文件包装后再上传。
FormData对象是HTML5新增的API,它可以很方便的创建包含文件、文本和其他数据项的表单,并将其发送给服务器。FormData对象可以被用在<form>
元素中,也可以被用在XMLHttpRequest
对象中。
前端文件上传
1. 创建<form>
元素
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="上传">
</form>
2. 使用FormData对象包装文件
const form = document.querySelector('form');
const formData = new FormData(form);
// 添加其他数据到FormData对象中
formData.append('name', 'John Doe');
formData.append('email', 'johndoe@example.com');
3. 发送FormData对象到服务器
fetch('/upload', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
console.log(data);
});
前端缩略图上传
1. 创建<canvas>
元素
<canvas id="canvas" width="100" height="100"></canvas>
2. 获取图片文件
const file = document.querySelector('input[type=file]').files[0];
3. 创建FileReader对象
const reader = new FileReader();
4. 将图片文件加载到FileReader对象中
reader.onload = function() {
const image = new Image();
image.onload = function() {
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
ctx.drawImage(image, 0, 0, 100, 100);
// 将canvas元素转换为DataURL
const dataURL = canvas.toDataURL('image/jpeg');
// 发送DataURL到服务器
fetch('/upload-thumbnail', {
method: 'POST',
body: dataURL
})
.then(response => response.json())
.then(data => {
console.log(data);
});
};
image.src = reader.result;
};
reader.readAsDataURL(file);
总结
本文介绍了前端文件上传和缩略图上传的详细步骤,并提供了代码示例。希望对读者有所帮助。