首頁  >  文章  >  web前端  >  HTML5上傳檔案顯示進度的實作程式碼_html5教學技巧

HTML5上傳檔案顯示進度的實作程式碼_html5教學技巧

WBOY
WBOY原創
2016-05-16 15:51:061518瀏覽

這裡我們是結合Asp.net MVC做為服務端,您也可以是其它的服務端語言。讓我們看面這個片斷的HTML:

複製代碼
代碼如下:

@using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" , id="form1"}))
{















}

相關的Javascript是這樣的:

複製程式碼
程式碼如下:

function fileed() >var file = document.getElementById('fileToUpload').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("fileToUpload", document.getElementById('fileToUpload').files[0]);
var xhr = new XMLHttpRequest();
xhr.upload.addEventList(upload. "progress", uploadProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", uploadFailed, false);
", uploadCanceled, false);
xhr.open("POST", "Home/Upload");
xhr.send(fd);
}
function uploadProgress(1t) {
if (evt.lengthComputable) {
var percentComplete = Math.round(evt.loaded * 100 / evt.total);
Compument.getElementById('progressNumber').innerHTML = percentlete.toString( ';
}
else {
document.getElementById('progressNumber').innerHTML = 'unable to compute';
}
}
function uploadComplete(evt)
function upload >/* This event is raised when the server send back a response */
alert(evt.target.responseText);
}
function uploadFailed(evt) {
}
function uploadFailed(evt) {
alert("There was an an error attempting to upload the file.");
}
function uploadCanceled(evt) {
alert("The upload has been canceled by the user or the browection dropped the connection.")

上面是就原生的Javascript,在onchange事件執行fileSelected的function,在點擊button執行了uploadFile的function,這裡使用XMLHttpRequest實作ajax上傳檔案。 注意程式碼在Firefox 14 可以工作,IE 9目前不支援file api,可以參加這裡。 服務端的代碼很簡單:

複製代碼
代碼如下:

public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
///
/// Uploads the specified files.
///

/// The files.
/// ActionResult
[HttpPost ]
public ActionResult Upload(HttpPostedFileBase[] fileToUpload)
{
foreach (HttpPostedFileBase file in fileToUpload)
{
string path = System.IO。 ~/App_Data"), System.IO.Path.GetFileName(file.FileName));
file.SaveAs(path);
}
ViewBag.Message = "File(s) uploaded successfully";
return RedirectToAction("Index");
}
}

作者:Petter Liu
陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn