HTML5_纯JS实现上传文件显示文件大小,文件信息,上传进度_不使用JS库

前台 html
<input type="file" id="_netLogo" onchange="fileSelected();">
<div id="fileName">
</div>
<div id="fileSize">
</div>
<div id="fileType">
</div>
<div id="progressNumber">
</div>
<button type="button" class="btn btn-default" onclick="uploadFile()">上传</button>

前台JS

<script type="text/javascript">

function fileSelected() {
var file = document.getElementById('_netLogo').files[0];
if (file) {
var fileSize = 0;
if (file.size > 1024 * 1024)
fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';
else
fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';

document.getElementById('fileName').innerHTML = 'Name: ' + file.name;
document.getElementById('fileSize').innerHTML = 'Size: ' + fileSize;
document.getElementById('fileType').innerHTML = 'Type: ' + file.type;
}
}

function uploadFile() {
var fd = new FormData();
fd.append("_netLogo", document.getElementById('_netLogo').files[0]);
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", uploadFailed, false);
xhr.addEventListener("abort", uploadCanceled, false);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.open("POST", "/User/WNetEdit2_test");
xhr.send(fd);
}

function uploadProgress(evt) {
if (evt.lengthComputable) {
var percentComplete = Math.round(evt.loaded * 100 / evt.total);
document.getElementById('progressNumber').innerHTML = percentComplete.toString() + '%';
}
else {
document.getElementById('progressNumber').innerHTML = 'unable to compute';
}
}

function uploadComplete(evt) {
/* This event is raised when the server send back a response */
alert(evt.target.responseText);
}

function uploadFailed(evt) {
alert("There was an error attempting to upload the file.");
}

function uploadCanceled(evt) {
alert("The upload has been canceled by the user or the browser dropped the connection.");
}
</script>

 

后台 测试函数

public string WNetEdit2_test()
{
var f = Request.Files[0];
string path = System.IO.Path.Combine(Server.MapPath("~/App_Data"), System.IO.Path.GetFileName(f.FileName));
f.SaveAs(path);
return "File(s) uploaded successfully";
}

 

你可能感兴趣的:(html5)