首頁 > web前端 > H5教程 > 主體

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

WBOY
發布: 2016-05-16 15:51:06
原創
1475 人瀏覽過

這裡我們是結合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
相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!