Ajax格局上传文件的章程,jQuery完结可拖动进度条实例代码

By admin in 4858美高梅 on 2019年7月7日

先给我们来得下效果图:

根据jQuery网页步骤流程进程条代码里面满含五款差异功用的jQuery步骤进程条特效。效果图如下:

html

jQuery Ajax方式上传文件用到三个对象

4858美高梅 1

4858美高梅 2

   <div class="progress">
   <div class="progress_bg">
    <div class="progress_bar"></div>
   </div>
   <div class="progress_btn"></div>
   <div class="text">0%</div>
  </div>

先是个对象:FormData

///作者:柯锦
///完成时间:2016.08.16
///多文件异步上传带进度条
(function ($) {
function bytesToSize(bytes) {
if (bytes === 0) return '0 B';
var k = 1024, // or 1000
sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
i = Math.floor(Math.log(bytes) / Math.log(k));
return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
}
function changeCursor(obj) {
obj.style.cursor = 'pointer'
}
function deleteSelfAndFile(obj) {
var that = $(obj);
var parentLi = that.parent("li");
that.remove();
parentLi.remove();
}
function CreateXMLHttpRequest(target) {
var xhr = new XMLHttpRequest();
//var ops = $.data(target, "KJajaxUpload").Options;
//var v, h, evs = { loadstart: 0, loadend: 0, progress: 0, load: 0, error: 0, abort: 0 };
//for (v in evs) {
// if (h = ops['on' + v]) {
// xhr.upload.addEventListener(v, h, false);
// }
//}
return xhr;
}
function InitFileDiv(target, options) {
var _that = $(target);
var width = _that.width();
var hasUploadedDiv = $("<div class='KJajaxUpload_HasUploaded'/>");
hasUploadedDiv.css({
width: "100%"
});
_that.append(hasUploadedDiv);// 上
var divClear = $("<div style='clear:both;'></div>");
var divUploadBody = $("<div class='KJajaxUpload_Body'/>");
var divLeft = $("<div class='KJajaxUpload_Left'/>");
var divRight = $("<div class='KJajaxUpload_Right'/>");
var uploadButton = $("<input type='button' class='KJajaxUpload_Button' value='Select File' />");
if (options.Text) {
uploadButton.val(options.Text);
}
uploadButton.click(function () {
SelectFiles(target);
})
uploadButton.css({
width: 80
})
if (options.Available) {
uploadButton.prop("disabled", false);
} else {
uploadButton.prop("disabled", true);
}
divUploadBody.css({
"overflow": "hidden"
})
divLeft.css({
float: "left",
width: "100%"
})
divRight.css({
float: "left",
"margin-left": " -20px"
})
_that.append(divClear);
divLeft.append(uploadButton);// 左 button
divLeft.append("<font style='font-size:12px;color:red;margin-left:2px;'>可多选</font>")
divUploadBody.append(divLeft);// 左
divUploadBody.append(divRight);// 右 文件列表
_that.append(divUploadBody);
return _that;
}
/// 创建蒙版
function CreateMark(target) {
var mark;
var width = $(document.body).width() / 2 - 200;
mark = $("<div>");
mark.css({
width: "100%",
height: "100%",
position: "fixed",
left: 0,
top: 0,
opacity: 0.5,
"z-index": 8,
"background-color": "#EFEFF2",
"display": "none"
});
var contentText = $("<div class='KJajaxUpload_upload_wrapper'>");
contentText.html("文件上传中,请稍后...");
contentText.css({
"text-align": "center",
width: "400px",
"padding-bottom": "50px",
"z-index": 9,
position: "fixed",
left: width + "px",
"top": "50%",
"background-color": "white",
"display": "none"
})
contentText.appendTo($("body"));
mark.appendTo($("body"));
return mark;
}
///创建进度条
function CreateUploadBar(target) {
var contentText = $(".KJajaxUpload_upload_wrapper");
var fileDiv = $(target);// $.data(target, "KJajaxUpload").FileDiv;
var FileList = fileDiv.find(".fileuploadlist.newfilelist");
$.each(FileList, function (i) {
var fileName = $(this).attr("filename");
var divid = $(this).attr("id");
var proressDiv = $("<div id='KJajaxUpload_progress_" + i + "' />");
var fileNameLable = $("" + fileName + "");
var barDiv = $("<div id='KJajaxUpload_bar_" + divid + "' name='KJajaxUpload_bar_" + fileName + "'/>");
barDiv.css({
width: "350px",
"margin-left": "20px",
height: "22px",
border: "1px solid black ",
"line-height": "22px"
})
var barText1 = $("<div class='KJajaxUpload_progresstext'/>");
barText1.css({
"text-align": "center",
"position": "absolute",
width: "350px"
});
barText1.html("0%");
var barText2 = $("<div class='KJajaxUpload_progresstext'/>");
barText2.css({
"text-align": "center",
width: "350px",
"background-color": "#ffe48d"
});
barText2.html("0%");
var barValue = $("<div class='KJajaxUpload_progressvalue'>");
barValue.css({
position: "relative",
overflow: "hidden",
width: "0px"
})
barValue.append(barText2);
barDiv.append(barText1);
barDiv.append(barValue);
proressDiv.append(fileNameLable);
contentText.append(proressDiv);
contentText.append(barDiv);
});
}
function ChangeProcess(filename, evt) {
var loaded = evt.loaded; //已经上传大小情况 
var tot = evt.total; //附件总大小 
var per = Math.floor(100 * loaded / tot); //已经上传的百分比 
var that = $("[name='KJajaxUpload_bar_" + filename + "']");
that.find('div.KJajaxUpload_progressvalue').css("width", per + "%");
that.find('div.KJajaxUpload_progresstext').html(per + "%");
}
///选择文件
function SelectFiles(target) {
var options = $.data(target, "KJajaxUpload").Options;
var deleteButtonUrl = options.deleteButtonUrl;
var ele = $("<input type='file'/>");
ele.prop("multiple", options.multiple !== false);
ele.hide();
ele.change(function (e) {
var exist = false;
var files = e.target.files;
var filenames = GetalreadyExistFileNames(target);
for (var item in files) {
var file = files[item];
if ($.inArray(file.name, filenames) > -1) {
exist = true;
break;
}
}
if (!exist) {
var ul = $("<ul style='margin:0px;'/>");
for (var i = 0, n = files.length; i < n; i++) {
var deletebutton = $("<img src='" + deleteButtonUrl + "' onmouseover='changeCursor(this)' class='deleteBtn' />");
deletebutton.click(function () {
deleteSelfAndFile(this);
})
var guid = new GUID().New();
var li = $('<li class="fileuploadlist newfilelist" id="' + guid + '" filename="' + files[i].name + '" >' + files[i].name + ' (' + bytesToSize(files[i].size) + ' )</li>');
li.append(deletebutton);
ul.append(li);
}
$(target).find(".KJajaxUpload_Right").append(ul);
options.onChange.call(this, e);
} else {
alert("文件名重复");
ele.remove();
return
}
});
$(target).append(ele);
ele.click();
}
/// 获取已经存在的文件名列表
function GetalreadyExistFileNames(target) {
var that = $(target);
var fileExists = that.find(".fileuploadlist");
var fileNames = [];
/// 还存在的文件列表
fileExists.each(function () {
var filename = $(this).attr("filename");
if ($.inArray(filename, fileNames) == -1) {
fileNames.push(filename);
}
})
return fileNames;
}
/// 上传文件
function UploadFiles(target) {
var that = $(target);
var fileInputs = that.find(":file");
var options = $.data(target, "KJajaxUpload").Options;
var deleteButtonUrl = options.deleteButtonUrl;
var onUploaded = options.onUploaded;
if (fileInputs.length > 0) {
var total = 0;
var uploaded = 0;
var reponses = [];
var mark = $.data(target, "KJajaxUpload").Mark;
var markcontent = $(".KJajaxUpload_upload_wrapper");
mark.show();
markcontent.show();
CreateUploadBar(target);
var fileExists = that.find(".fileuploadlist");
var fileNames = [];
/// 还存在的文件列表
fileExists.each(function () {
var filename = $(this).attr("filename");
if ($.inArray(filename, fileNames) == -1) {
fileNames.push(filename);
}
})
for (var i = 0; i < fileInputs.length; i++) {
var fileinput = fileInputs[i];
var files = fileinput.files;
if (files.length > 0) {
for (var j = 0, n = files.length; j < n; j++) {
if ($.inArray(files[j].name, fileNames) > -1) {
total++;
var filename = files[j].name;
var paramData = options.formData;
var data = new FormData();
data.append("uploadedfile[" + j + "]", files[j]);
if (paramData != null) {
for (var k in paramData) {
data.append(k, paramData[k]);
}
}
var xhr = CreateXMLHttpRequest(target);
xhr.upload.addEventListener("progress",
function (data) {
return function (e) {
ChangeProcess(data, e);
}
}(filename), false);
xhr.upload.addEventListener("loadend", function () {
}, false);
xhr.upload.addEventListener("load", function () {
uploaded++;
}, false);
xhr.onreadystatechange = function () {
if (this.readyState == 4) {// 4 = "loaded"
if (this.status == 200) {// 200 = OK 
reponses.push(this.responseText);
if (uploaded == $.data(target, "KJajaxUpload").TotalFiles) {
var HasUploaded = that.find(".KJajaxUpload_HasUploaded");
var ul = $("<ul style='margin:0px;'/>");
for (var t = 0; t < reponses.length; t++) {
var files = JSON.parse(reponses[t]);
for (var i = 0, n = files.length; i < n; i++) {
var deletebutton = $("<img src='" + deleteButtonUrl + "' onmouseover='changeCursor(this)' class='deleteBtn' />");
deletebutton.click(function () {
deleteSelfAndFile(this);
})
var guid = new GUID().New();
var li = $('<li class="fileuploadlist" id="' + guid + '" filename="' + files[i].Name + '" filepath="' + files[i].FilePath + '" ><a target="_blank" href="' + files[i].FileUrl + '">' + files[i].Name + '</a> </li>');
li.append(deletebutton);
ul.append(li);
}
}
that.find(".KJajaxUpload_Right").empty();
HasUploaded.append(ul);
fileInputs.remove();
Uploaded(target);
var data = GetAlreadyUploadedFiles(target);
onUploaded.call(null, data);
}
}
else {
alert("Problem retrieving XML data");
}
}
};
xhr.open("POST", options.url, true);
xhr.send(data);
}
}
var state = $.data(target, "KJajaxUpload");
state.TotalFiles = total;
$.data(this, "KJajaxUpload", state);
}
}
} else {
var data = GetAlreadyUploadedFiles(target);
onUploaded.call(null, data);
}
return that;
}
/// 上传完毕
function Uploaded(target) {
alert("文件上传完毕");
var mark = $.data(target, "KJajaxUpload").Mark;
var markcontent = $(".KJajaxUpload_upload_wrapper");
mark.hide();
markcontent.hide();
var that = $(target);
var fileInputs = that.find(":file");
fileInputs.remove();
}
///初始化已有的数据
function AlreadFiles(target, options) {
var that = $(target);
var deleteButtonUrl = options.deleteButtonUrl;
var files = options.AlreadFiles;
var HasUploaded = that.find(".KJajaxUpload_HasUploaded");
if (files.length > 0) {
var ul = $("<ul style='margin:0px;'/>");
for (var i = 0, n = files.length; i < n; i++) {
var deletebutton = $("<img src='" + deleteButtonUrl + "' onmouseover='changeCursor(this)' class='deleteBtn' />");
deletebutton.click(function () {
deleteSelfAndFile(this);
})
var pos = files[i].lastIndexOf("\\");
var filepos = files[i].lastIndexOf("uploadFile");
var reg = /[\\\/]/g;
var filePath = files[i];
var fileUrl = files[i].substr(filepos).replace(reg, '/');
var fileName = files[i].substr(pos + 1);
fileName = fileName.substr(fileName.lastIndexOf("_S_") + 3);
var guid = new GUID().New();
var li = $('<li class="fileuploadlist" id="' + guid + '" filename="' + fileName + '" filepath="' + filePath + '" ><a target="_blank" href="' + fileUrl + '">' + fileName + '</a> </li>');
li.append(deletebutton);
ul.append(li);
}
HasUploaded.append(ul);
}
}
function GetAlreadyUploadedFiles(target) {
var that = $(target);
var HasUploaded = that.find(".KJajaxUpload_HasUploaded li");
var datas = [];
HasUploaded.each(function () {
var data = {};
data.name = $(this).attr("filename");
data.filepath = $(this).attr("filepath");
data.fileurl = $(this).find("a").attr("href");
datas.push(data);
})
return datas;
}
$.fn.KJajaxUpload = function (options, param) {
var that = this;
if (typeof options == "string") {
var method = $.fn.KJajaxUpload.Methods[options];
if (method) {
return method(this, param);
}
}
options = options || {};
return this.each(function () {
var that = this;
var state = $.data(this, "KJajaxUpload");
if (state) {
$.extend(state.Options, options);
} else {
var _options = $.extend({}, $.fn.KJajaxUpload.Default, options);
InitFileDiv(this, _options);
AlreadFiles(this, _options);
state = $.data(this, "KJajaxUpload", {
Options: _options,
Mark: CreateMark(this),
TotalFiles: 0
});
}
})
}
$.fn.KJajaxUpload.Default = {
url: '/Ashx/UploadFilesHandler.ashx?r=' + Math.random(),
formData: {},//要传递的参数
Text: "选择文件",
ContinueAddText: "继续添加",
multiple: true,
AlreadFiles: [],// 初始化已经存在的文件
Available: true,// 可用的
deleteButtonUrl: '/Style/images/delete.jpg',
onInit: function () { },
onChange: function () { },
onUploaded: function () { }// 文件上传完毕后的回调函数
};
$.fn.KJajaxUpload.Methods = {
options: function (jq) {
return $.data(jq[0], "KJajaxUpload").Options;
},
upload: function (jq) {
return UploadFiles(jq[0]);
}
};
})(jQuery)

在线预览4858美高梅 ,      
源码下载.rar)

Ajax格局上传文件的章程,jQuery完结可拖动进度条实例代码。css

其次个对象:XMLHttpRequest

后端代码

html代码:

  .progress{position: relative; width:300px;margin:100px auto;}
  .progress_bg{height: 10px; border: 1px solid #ddd; border-radius: 5px; overflow: hidden;background-color:#f2f2f2;}
  .progress_bar{background: #5FB878; width: 0; height: 10px; border-radius: 5px;}
  .progress_btn{width: 20px; height: 20px; border-radius: 5px; position: absolute;background:#fff; 
  left: 0px; margin-left: -10px; top:-5px; cursor: pointer;border:1px #ddd solid;box-sizing:border-box;}
  .progress_btn:hover{border-color:#F7B824;}

当下新版的Firefox 与 Chrome
等帮忙HTML5的浏览器完美的支撑那八个指标,但IE9尚未帮衬 FormData
对象,还在用IE6 ? 只好望眼欲穿….

/// <summary>
/// UploadFilesHandler 的摘要说明
/// </summary>
public class UploadFilesHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
List<FileReponse> list = new List<FileReponse>();
string filePath = System.AppDomain.CurrentDomain.BaseDirectory.ToString() + @"uploadFile\" + DateTime.Now.Year.ToString() + @"\" + DateTime.Now.Month.ToString() + @"\" + DateTime.Now.Day.ToString() + @"\" + System.Web.HttpUtility.UrlDecode(context.Request.Params["userName"].ToString()) + @"\";
if (context.Request.Files.Count > 0)
{
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
try
{
foreach (string files in context.Request.Files)
{
HttpPostedFile upfile = context.Request.Files[files];
int bufferSize = 1024 * 50;//50K
string _guid = Guid.NewGuid().ToString().Replace("-", "");
byte[] buffer = new byte[bufferSize];
int currentCounts = 0;//
long totalLength = upfile.ContentLength;
string name = upfile.FileName.Substring(upfile.FileName.LastIndexOf("\\") + 1);
string fileName = filePath + _guid + "_S_" + name;
using (FileStream fs = new FileStream(fileName, FileMode.Create))
{
while (currentCounts < totalLength)
{
int bytes = upfile.InputStream.Read(buffer, 0, bufferSize);
fs.Write(buffer, 0, bytes);
//Thread.Sleep(1);//0.001s
currentCounts += bytes;
}
}
FileReponse item = new FileReponse();
item.Name = name;
item.FilePath = fileName;
int filepos = item.FilePath.LastIndexOf("uploadFile");
item.FileUrl = item.FilePath.Substring(filepos);
list.Add(item);
}
}
catch (Exception ex)
{
}
}
string reponse = JsonConvert.SerializeObject(list);
context.Response.Write(reponse);
//context.Response.ContentType = "text/plain";
//context.Response.Write("Hello World");
}
public bool IsReusable
{
get
{
return false;
}
}
}
internal class FileReponse
{
public string Name { get; set; }
public string FilePath { get; set; }
public string FileUrl { get; set; }
}
<div class="step_context test"></div>
当前步骤:
第<input type="text" value="5" id="currentStepVal" />步 <button onclick="StepTool.drawStep(jQuery('#currentStepVal').val(),stepListJson);" type="button">重新生成</button>
<script type="text/javascript">
  //所有步骤的数据
  var stepListJson = [{ StepNum: 1, StepText: "第一步" },
  { StepNum: 2, StepText: "第二步" },
  { StepNum: 3, StepText: "第三步" },
  { StepNum: 4, StepText: "第四步" },
  { StepNum: 5, StepText: "第五步" },
  { StepNum: 6, StepText: "第六步" },
  { StepNum: 7, StepText: "第七步" }];
  //当前进行到第几步
  var currentStep = 5;
  //new一个工具类
  var StepTool = new Step_Tool_dc("test", "mycall");
  //使用工具对页面绘制相关流程步骤图形显示
  StepTool.drawStep(currentStep, stepListJson);
  //回调函数
  function mycall(restult) {
    // alert("mycall"+result.value+":"+result.text);
    StepTool.drawStep(result.value, stepListJson);
    //TODO...这里可以填充点击步骤的后加载相对应数据的代码
  }
</script>

js 

有了那七个指标,大家得以真正的贯彻Ajax方式上传文件。

使用:

上述代码正是小编给大家大饱眼福的依照jquery步骤进程条源码分享,希望大家欣赏。

$(function(){
    var tag = false,ox = 0,left = 0,bgleft = 0;
    $('.progress_btn').mousedown(function(e) {
     ox = e.pageX - left;
     tag = true;
    });
    $(document).mouseup(function() {
     tag = false;
    });
    $('.progress').mousemove(function(e) {//鼠标移动
     if (tag) {
      left = e.pageX - ox;
      if (left <= 0) {
       left = 0;
      }else if (left > 300) {
       left = 300;
      }
      $('.progress_btn').css('left', left);
      $('.progress_bar').width(left);
      $('.text').html(parseInt((left/300)*100) + '%');
     }
    });
    $('.progress_bg').click(function(e) {//鼠标点击
     if (!tag) {
      bgleft = $('.progress_bg').offset().left;
      left = e.pageX - bgleft;
      if (left <= 0) {
       left = 0;
      }else if (left > 300) {
       left = 300;
      }
      $('.progress_btn').css('left', left);
      $('.progress_bar').animate({width:left},300);
      $('.text').html(parseInt((left/300)*100) + '%');
     }
    });
   });

示范代码:

var config = {};
config.formData = formData;
if (!HasTheRight("HDComplaintsArea")) {
config.Available = false;
}
if (record.Attachments) {
config.AlreadFiles = record.Attachments;
}
config.onUploaded = function (data) {
save(data);
}
$("#filediv").KJajaxUpload(config);
$("#btnSave").click(function () {
$("#filediv").KJajaxUpload("upload");
})
function save(data) {
fields.Attachments = [];
for (var i = 0; i < data.length; i++) {
fields.Attachments.push(data[i].filepath);
} 
fields.Attachments = JSON.stringify(fields.Attachments);
}

您恐怕感兴趣的篇章:

  • jquery彩色投票进度条轻便实例演示
  • jquery完毕加载进程条提示成效
  • jQuery实现轻便的文件上传进程条效果
  • jquery完毕模拟百分比进程条渐变效果代码
  • 使用jQuery实现优秀的圆形进度条倒计时插件
  • jQuery带进程条全屏图片轮播特效代码分享
  • jQuery实现文件上传进程条特效
  • jquery插件NProgress.js制作网页加载进程条
  • Jquery
    Uploadify上传带进程条的简便实例
  • jQuery完成页面顶端展现的进程条效果总体实例

效果图

<!DOCTYPE html>
<html>
<head>
 <title>Html5 Ajax 上传文件</title>
 <script type="text/javascript">
  function UpladFile() {
   var fileObj = document.getElementByIdx_x_x("file").files[0]; // 获取文件对象
   var FileController = "../file/save";     // 接收上传文件的后台地址 
   // FormData 对象
   var form = new FormData();
   form.append("author", "hooyes");      // 可以增加表单数据
   form.append("file", fileObj);       // 文件对象
   // XMLHttpRequest 对象
   var xhr = new XMLHttpRequest();
   xhr.open("post", FileController, true);
   xhr.onload = function () {
    alert("上传完成!");
   };
   xhr.send(form);
  }
</script>
</head>
<body>
<input type="file" id="file" name="myfile" />
<input type="button" onclick="UpladFile()" value="上传" />
</body>
</html>

上述所述是笔者给大家介绍的jQuery多文件异步上传带进程条实例代码,希望对我们享有补助,假使大家有别的疑问请给本人留言,小编会及时回复大家的。在此也特别谢谢我们对剧本之家网址的辅助!

4858美高梅 3

很简短的代码,便足以高达Ajax方式上传文件,上边的代码中运用<input
type=”file”
/>这种价值观的取舍文件的法子爆发文书对象,HTML5还扶助使用二种更加灵敏的主意,如拖拽文件到内定的因素上发生。

您大概感兴趣的稿子:

  • jQuery完结公文上传进程条特效
  • jQuery完成简单的文本上传进程条效果
  • 基于Jquery插件Uploadify实现实时体现进程条上传图片
  • jQuery监听文件上传完结进程条效果的艺术

落到实处原理

Ajax已成功上传文件,但那时大家会想到二个标题,如何显示进程条?带着那个难点,脑子会想到,Flash?
浏览器插件?。

  首先是用mousedown()鼠标按下事件保存三个景况值,mouseup()鼠标抬起事件撤消该境况,再同时包容mousemove()鼠标移动事件,达成按住拖动的效应。

NO,以后无需那么些事物了。

在鼠标移动的同期去改动精度条的长短和按键的相对左部的离开。

始于动手,先做三个进程条,进度条也很轻便,使用HTML5 新加的价签:

  然后便是偏离的估测计算,首要运用的正是pageX()
属性。pageX是鼠标指针相对于文书档案的侧边缘的任务。在鼠标按下是就记录相对地方,在鼠标移动后就可求出鼠标移动的离开。进而退换按键地方和进程条长度。

<progress id="progressBar" value="0" max="100"> </progress>

如上所述是小编给大家介绍的jQuery实现可拖动进程条demo,希望对大家具备援救,假使我们有其它疑问请给自个儿留言,我会及时过来大家的。在此也特别多谢大家对台本之家网址的支撑!

其一在浏览器中便会表现了一个进程条,以往我们要做的正是在上传的时候,实时的去改变它的Value值,然后进程展现的主题素材便付给它了。

您只怕感兴趣的小说:

  • jquery
    实现拖动文件上传加载进程条功效
  • jquery
    轻松的进程条完成代码
  • 6款新颖的jQuery和CSS3进度条插件推荐
  • 享受8款特出的 jQuery
    加载动画和进程条插件
  • 听说HTML5
    Ajax文件上传进程条怎样促成(jquery版本)
  • Jquery进度条插件 Progress
    Bar小意思消除
  • Jquery
    Uploadify上传带进程条的简约实例
  • jQuery
    页面载入进程条完结代码
  • 用jQuery模拟页面加载进程条的落到实处代码
  • jQuery轻便贯彻提交数据出现loading过程条的主意
  • jQuery实现的手动拖动调整进程条效果示例【测验可用】

咱俩的劳动器端没有要求修改,只需求在JS中XHRubicon对象加三个风云。

xhr.upload.addEventListener("progress", progressFunction, false)

progressFunction
被调用的时候会传进三个事件目的,这些指标有八个属性,叁个正是loaded
三个是total ,分别代表,已上传的值,和总要上传的值。

那多亏我们需求的,所以这些艺术,能够那样写:

function progressFunction(evt) {
   var progressBar = document.getElementByIdx_x_x("progressBar");
   if (evt.lengthComputable) {
    progressBar.max = evt.total;  
    progressBar.value = evt.loaded;
   }
  }

像这种类型便得以产生,上传进程显示了。

如下针对地方的首先个示范代码,做三个调动:

演示代码2,带进度展现:

<!DOCTYPE html>
<html>
<head>
 <title>Html5 Ajax 上传文件</title>
 <script type="text/javascript">
  function UpladFile() {
   var fileObj = document.getElementByIdx_x_x("file").files[0]; // js 获取文件对象
   var FileController = "../file/save";     // 接收上传文件的后台地址 
   // FormData 对象
   var form = new FormData();
   form.append("author", "hooyes");      // 可以增加表单数据
   form.append("file", fileObj);       // 文件对象
   // XMLHttpRequest 对象
   var xhr = new XMLHttpRequest();
   xhr.open("post", FileController, true);
   xhr.onload = function () {
    // alert("上传完成!");
   };
   xhr.upload.addEventListener("progress", progressFunction, false);
   xhr.send(form);
  }
  function progressFunction(evt) {
   var progressBar = document.getElementByIdx_x_x("progressBar");
   var percentageDiv = document.getElementByIdx_x_x("percentage");
   if (evt.lengthComputable) {
    progressBar.max = evt.total;
    progressBar.value = evt.loaded;
    percentageDiv.innerHTML = Math.round(evt.loaded / evt.total * 100) + "%";
   }
  } 
 </script>
</head>
<body>
 <progress id="progressBar" value="0" max="100">
 </progress>

 <br />
 <input type="file" id="file" name="myfile" />
 <input type="button" onclick="UpladFile()" value="上传" />
</body>
</html>

 后台接收文件的次序可以是任何语言(C#,PHP,Python
等)编写的,上述例子使用C#

很轻巧,不供给为这一个进程条做别的变动。

var flist = Request.Files;
   for (int i = 0; i < flist.Count; i++)
   {
    string FilePath = "E:\\hooyes\\Files\\";
    var c = flist[i];
    FilePath = Path.Combine(FilePath, c.FileName);
    c.SaveAs(FilePath);
   }

如上所述是小编给我们介绍的jQuery
Ajax格局上传文件的法子,希望对大家具备帮忙,如若大家有别的疑窦迎接给我留言,小编会及时还原大家的!

你也许感兴趣的文章:

  • jQuery Ajax
    上传文件管理形式介绍(推荐)
  • jQuery插件ajaxfileupload.js完毕上传文件
  • 依据jQuery
    Ajax实现上传文件
  • PHP结合jQuery插件ajaxFileUpload达成异步上传文件实例
  • jQuery异步上传文件插件ajaxFileUpload详细介绍
  • JQuery插件ajaxfileupload.js异步上传文件实例
  • jQuery插件ajaxFileUpload完结异步上传文件效果
  • 三个简易的jQuery插件ajaxfileupload.js完成ajax上传文件例子

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图
Copyright @ 2010-2019 美高梅手机版4858 版权所有