HTML5上傳文件顯示進(jìn)度的實(shí)現(xiàn)代碼
發(fā)布時(shí)間:2012-08-30 11:48:06 作者:佚名
我要評(píng)論

下面我們使用Html 5的新特性file api實(shí)現(xiàn)上傳文件,并顯示上傳文件進(jìn)度百分比。意圖是這樣的,當(dāng)選擇文件時(shí),顯示當(dāng)前文件信息
這里我們是結(jié)合Asp.net MVC做為服務(wù)端,您也可以是其它的服務(wù)端語(yǔ)言。讓我們看面這個(gè)片斷的HTML:
@using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" , id="form1"}))
{
<div class="row">
<label for="file">
Upload Image:</label>
<input type="file" name="fileToUpload" id="fileToUpload" multiple="multiple" onchange="fileSelected();" />
</div>
<div id="fileName">
</div>
<div id="fileSize">
</div>
<div id="fileType">
</div>
<div class="row">
<input type="button" onclick="uploadFile()" value="Upload Image" />
</div>
<div id="progressNumber">
</div>
}
相關(guān)的Javascript是這樣的:
function fileSelected() {
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.addEventListener("progress", uploadProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", uploadFailed, false);
xhr.addEventListener("abort", uploadCanceled, false);
xhr.open("POST", "Home/Upload");
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.");
}
上面是就原生的Javascript,在onchange事件執(zhí)行fileSelected的function,在點(diǎn)擊button執(zhí)行了uploadFile的function,這里使用XMLHttpRequest實(shí)現(xiàn)ajax上傳文件。 注意代碼在Firefox 14 可以工作,IE 9目前不支持file api,可以參加這里。 服務(wù)端的代碼很簡(jiǎn)單:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
/// <summary>
/// Uploads the specified files.
/// </summary>
/// <param name="fileToUpload">The files.</param>
/// <returns>ActionResult</returns>
[HttpPost]
public ActionResult Upload(HttpPostedFileBase[] fileToUpload)
{
foreach (HttpPostedFileBase file in fileToUpload)
{
string path = System.IO.Path.Combine(Server.MapPath("~/App_Data"), System.IO.Path.GetFileName(file.FileName));
file.SaveAs(path);
}
ViewBag.Message = "File(s) uploaded successfully";
return RedirectToAction("Index");
}
}
作者:Petter Liu
復(fù)制代碼
代碼如下:@using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" , id="form1"}))
{
<div class="row">
<label for="file">
Upload Image:</label>
<input type="file" name="fileToUpload" id="fileToUpload" multiple="multiple" onchange="fileSelected();" />
</div>
<div id="fileName">
</div>
<div id="fileSize">
</div>
<div id="fileType">
</div>
<div class="row">
<input type="button" onclick="uploadFile()" value="Upload Image" />
</div>
<div id="progressNumber">
</div>
}
相關(guān)的Javascript是這樣的:
復(fù)制代碼
代碼如下:function fileSelected() {
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.addEventListener("progress", uploadProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", uploadFailed, false);
xhr.addEventListener("abort", uploadCanceled, false);
xhr.open("POST", "Home/Upload");
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.");
}
上面是就原生的Javascript,在onchange事件執(zhí)行fileSelected的function,在點(diǎn)擊button執(zhí)行了uploadFile的function,這里使用XMLHttpRequest實(shí)現(xiàn)ajax上傳文件。 注意代碼在Firefox 14 可以工作,IE 9目前不支持file api,可以參加這里。 服務(wù)端的代碼很簡(jiǎn)單:
復(fù)制代碼
代碼如下:public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
/// <summary>
/// Uploads the specified files.
/// </summary>
/// <param name="fileToUpload">The files.</param>
/// <returns>ActionResult</returns>
[HttpPost]
public ActionResult Upload(HttpPostedFileBase[] fileToUpload)
{
foreach (HttpPostedFileBase file in fileToUpload)
{
string path = System.IO.Path.Combine(Server.MapPath("~/App_Data"), System.IO.Path.GetFileName(file.FileName));
file.SaveAs(path);
}
ViewBag.Message = "File(s) uploaded successfully";
return RedirectToAction("Index");
}
}
作者:Petter Liu
相關(guān)文章
使用Html5實(shí)現(xiàn)異步上傳文件,支持跨域,帶有上傳進(jìn)度條
下面小編就為大家?guī)?lái)一篇使用Html5實(shí)現(xiàn)異步上傳文件,支持跨域,帶有上傳進(jìn)度條。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2016-09-17- 本篇文章主要介紹了HTML5拖拉上傳文件的簡(jiǎn)單實(shí)例,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-01-11
HTML5+WebSocket實(shí)現(xiàn)多文件同時(shí)上傳的實(shí)例
本篇文章主要介紹了HTML5-WebSocket實(shí)現(xiàn)多文件同時(shí)上傳的實(shí)例,HTML5結(jié)合Websocket進(jìn)行文件的傳輸就變得更加方便和靈活,有興趣的可以了解一下。2016-12-29html5 實(shí)現(xiàn)客戶端驗(yàn)證上傳文件的大小(簡(jiǎn)單實(shí)例)
下面小編就為大家?guī)?lái)一篇html5 實(shí)現(xiàn)客戶端驗(yàn)證上傳文件的大小(簡(jiǎn)單實(shí)例)。小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2016-05-15html5拍照功能實(shí)現(xiàn)代碼(htm5上傳文件)
在HTML5規(guī)范的支持下,WebApp在手機(jī)上拍照已經(jīng)成為可能。在下面,我將講解Web App如何用手機(jī)進(jìn)行拍照,顯示在頁(yè)面上并上傳到服務(wù)器2013-12-11input file上傳文件樣式支持html5的瀏覽器解決方案
最近在使用file上傳控件,發(fā)現(xiàn)了file上傳控件的兩個(gè)兼容性問(wèn)題:一個(gè)是file上傳控件在火狐下無(wú)法通過(guò)css改變width,另一個(gè)是file上傳控件在不同的瀏覽器下的外觀和行為都不2012-11-14- 本文簡(jiǎn)單介紹利用Html5的FormData實(shí)現(xiàn)文件的異步上傳,還可以實(shí)現(xiàn)上傳進(jìn)度條和文件大小驗(yàn)證等,代碼簡(jiǎn)單易懂,非常不錯(cuò),具有參考借鑒價(jià)值,需要的的朋友參考下吧2017-05-19