js文件上传

在web应用程序中使用文件

选择文件

1
<input type="file" id="input">
1
const selectedFile = document.getElementById('input').files[0];

通过事件选择文件

1
2
3
document.getElementById('input').addEventListener('change',function(e){
const file = this.files[0]
})

上传选择的文件

1
2
3
4
5
6
7
8
const input = document.getElementById('input')
const fd = new FormData();
fd.append('data', input.files[0]);

fetch('http://xxx.xxx.xxx', {
method: 'POST',
body:fd
}).then(res => res.json())

创建文件并上传

Blob

1
2
3
4
5
6
7
8
9
const input = document.getElementById('input')
const fd = new FormData();
const blob = new Blob(["[]"], { type: 'plain/text' });
fd.append('data', blob,'script.txt');

fetch('http://xxx.xxx.xxx', {
method: 'POST',
body:fd
}).then(res => res.json())
打赏
  • 版权声明: 本博客所有文章除特别声明外,著作权归作者所有。转载请注明出处!
  • Copyrights © 2015-2025 SunZhiqi

此时无声胜有声!

支付宝
微信