JavaScript FileApi简单介绍--使用XMLHttpRequest完成文件上传

本文介绍了一个使用JavaScript实现的文件上传与读取功能。通过FileReader API读取文件内容,并利用XMLHttpRequest发送二进制数据到服务器。文章还包含了完整的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

141917_RN2S_1011578.png

读取文件并上传的 JavaScript 函数
function uploadAndSubmit() { 
 var form = document.forms["demoForm"]; 
    
 if (form["file"].files.length > 0) { 
 // 寻找表单域中的 <input type="file" ... /> 标签
 var file = form["file"].files[0]; 
 // try sending 
 var reader = new FileReader(); 

 reader.onloadstart = function() { 
 // 这个事件在读取开始时触发
 console.log("onloadstart"); 
 document.getElementById("bytesTotal").textContent = file.size; 
 } 
 reader.onprogress = function(p) { 
 // 这个事件在读取进行中定时触发
 console.log("onprogress"); 
 document.getElementById("bytesRead").textContent = p.loaded; 
 } 

 reader.onload = function() { 
    // 这个事件在读取成功结束后触发
 console.log("load complete"); 
 } 

 reader.onloadend = function() { 
    // 这个事件在读取结束后,无论成功或者失败都会触发
 if (reader.error) { 
 console.log(reader.error); 
 } else { 
 document.getElementById("bytesRead").textContent = file.size; 
 // 构造 XMLHttpRequest 对象,发送文件 Binary 数据
 var xhr = new XMLHttpRequest(); 
 xhr.open(/* method */ "POST", 
 /* target url */ "upload.jsp?fileName=" + file.name 
 /*, async, default to true */); 
 xhr.overrideMimeType("application/octet-stream"); 
 xhr.sendAsBinary(reader.result); 
 xhr.onreadystatechange = function() { 
 if (xhr.readyState == 4) { 
 if (xhr.status == 200) { 
 console.log("upload complete"); 
 console.log("response: " + xhr.responseText); 
 } 
 } 
 } 
 } 
 } 

 reader.readAsBinaryString(file); 
 } else { 
 alert ("Please choose a file."); 
 } 
 }

更详细的信息请参阅原文

转载于:https://my.oschina.net/sskxyz/blog/662949

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值