记录一下,Javascript加asp.net实现多文件上传的方法。首先看一下要实现的功能,图片比文字描述更直观。
一、前台代码
前台代码代码分为三个部分,一是HTML代码,二是Style样式代码,三是Javascript代码。
1.html代码
在html中加入file控件,multiple设置为multiple,该控件主要是实现图片文件多选,并返回所选数据。
添加2个DIV标签,一个ID设置为“progressBar”,用来显示上传进度。该标签包含两个子DIV标签,一个图形显示进度,一个文字显示进度。另一个ID设置为“picBox”,用来显示上传完成后的图片。具体代码如下:
<div>
<input id="File1" type="file" multiple="multiple" onchange="UpLoad(this)"/><br />
<div id="progressBar">
<div id="progressBarImg"></div>
<div id="progressBarTxt">0%</div>
</div>
<div id="picBox"></div>
</div>
2.Style样式代码
progressBar定义进度条样式;progressBarImg 定义图片进度显示样式;
progressBarTxt 定义文字进度显示样式;delbt定义删除按钮样式。
<style>
#progressBar{width:200px;border:1px solid #000000;height:30px;position:relative;}
#progressBarImg {
width:0%;background-color:#00ff21;height:30px;position:absolute;z-index:3;
}
#progressBarTxt {
height:30px;position:absolute;z-index:4;text-align:center;
}
.delbt{position:absolute;border-radius:50%;width:25px;height:25px;background:#ff6a00;color:#ffffff;text-align:center;line-height:25px;cursor:pointer;}
#picBox li{position:relative;list-style:none;padding:3px;margin:0px;height:100px;width:100px;display:block;float:left;}
#picBox li img{position:absolute;height:100px;width:100px}
</style>
3.Javascript代码
领域XMLHttpRequest向后台提交数据,后台实现图片文件保存删除功能,代码中标有详细解释,具体代码如下:
<script type="text/javascript">
var xhr;
var progressBarTxt = document.getElementById("progressBarTxt");
var progressBarImg = document.getElementById("progressBarImg");
var picBox = document.getElementById("picBox");
function UpLoad(obj) {
progressBarTxt.innerHTML = "0%";
progressBarImg.style.width = "0%"
var formData = new FormData(); // FormData 对象
for (var i = 0; i < obj.files.length; i++) {
formData.append("files[]", obj.files[i]);
}
xhr = new XMLHttpRequest(); // XMLHttpRequest 对象
xhr.onreadystatechange = function () {//设置回调函数,请求状态readyState=4准备就绪,服务器返回的状态码status=200接收成功
// if (xhr.readyState === 4 && xhr.status === 200) { console.log(xhr.responseText) }
}
xhr.open("POST", "ImgUp.aspx", true);//post方式,url为服务器请求地址,true 该参数规定请求是否异步处理。
xhr.upload.addEventListener("progress", function (e) {//监听上传进度
//if (e.lengthComputable) {
// console.log("percent: ", (e.loaded / e.total) * 100 + "%");
//}
}, false);
xhr.onload = uploadComplete; //请求完成
xhr.onerror = uploadFailed; //请求失败
xhr.upload.onprogress = progressFunction;//上传进度调用方法实现
xhr.upload.onloadstart = function () {//上传开始执行方法
startTime = new Date().getTime(); //设置上传开始时间
startSize = 0;//设置上传开始时,以上传的文件大小为0
};
xhr.send(formData);
}
function progressFunction(evt) {
progressBarTxt.innerHTML = Math.round(evt.loaded / evt.total * 100) + "%";
progressBarImg.style.width = Math.round(evt.loaded / evt.total * 100) + "%"
}
function uploadComplete(evt) {
var temstr = xhr.responseText.split(',');
for (var i = 0; i < temstr.length; i++) {
var li = document.createElement("li");
li.innerHTML = "<img src='" + temstr[i] + "'/><span class='delbt' οnclick='deletePic(this,\"" + temstr[i] +"\")'>X</span>";
picBox.appendChild(li);
}
}
function uploadFailed(evt) { alert("上传失败!"); }
function deletePic(obj,picurl) {
var xhrD = new XMLHttpRequest();
xhrD.open("get", "ImgDelete.aspx?f=" + picurl, true);
xhrD.onload = function () {
obj.parentElement.remove();
}
xhrD.onerror = function () { }
xhrD.send();
}
</script>
4.整个前台代码
整个aspx文件代码如下:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<style>
#progressBar{width:200px;border:1px solid #000000;height:30px;position:relative;}
#progressBarImg {
width:0%;background-color:#00ff21;height:30px;position:absolute;z-index:3;
}
#progressBarTxt {
height:30px;position:absolute;z-index:4;text-align:center;
}
.delbt{position:absolute;border-radius:50%;width:25px;height:25px;background:#ff6a00;color:#ffffff;text-align:center;line-height:25px;cursor:pointer;}
#picBox li{position:relative;list-style:none;padding:3px;margin:0px;height:100px;width:100px;display:block;float:left;}
#picBox li img{position:absolute;height:100px;width:100px}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="File1" type="file" multiple="multiple" onchange="UpLoad(this)"/><br />
<div id="progressBar">
<div id="progressBarImg"></div>
<div id="progressBarTxt">0%</div>
</div>
<div id="picBox"></div>
</div>
<script type="text/javascript">
var xhr;
var progressBarTxt = document.getElementById("progressBarTxt");
var progressBarImg = document.getElementById("progressBarImg");
var picBox = document.getElementById("picBox");
function UpLoad(obj) {
progressBarTxt.innerHTML = "0%";
progressBarImg.style.width = "0%"
var formData = new FormData(); // FormData 对象
for (var i = 0; i < obj.files.length; i++) {
formData.append("files[]", obj.files[i]);
}
xhr = new XMLHttpRequest(); // XMLHttpRequest 对象
xhr.onreadystatechange = function () {//设置回调函数,请求状态readyState=4准备就绪,服务器返回的状态码status=200接收成功
// if (xhr.readyState === 4 && xhr.status === 200) { console.log(xhr.responseText) }
}
xhr.open("POST", "ImgUp.aspx", true);//post方式,url为服务器请求地址,true 该参数规定请求是否异步处理。
xhr.upload.addEventListener("progress", function (e) {//监听上传进度
//if (e.lengthComputable) {
// console.log("percent: ", (e.loaded / e.total) * 100 + "%");
//}
}, false);
xhr.onload = uploadComplete; //请求完成
xhr.onerror = uploadFailed; //请求失败
xhr.upload.onprogress = progressFunction;//上传进度调用方法实现
xhr.upload.onloadstart = function () {//上传开始执行方法
startTime = new Date().getTime(); //设置上传开始时间
startSize = 0;//设置上传开始时,以上传的文件大小为0
};
xhr.send(formData);
}
function progressFunction(evt) {
progressBarTxt.innerHTML = Math.round(evt.loaded / evt.total * 100) + "%";
progressBarImg.style.width = Math.round(evt.loaded / evt.total * 100) + "%"
}
function uploadComplete(evt) {
var temstr = xhr.responseText.split(',');
for (var i = 0; i < temstr.length; i++) {
var li = document.createElement("li");
li.innerHTML = "<img src='" + temstr[i] + "'/><span class='delbt' οnclick='deletePic(this,\"" + temstr[i] +"\")'>X</span>";
picBox.appendChild(li);
}
}
function uploadFailed(evt) { alert("上传失败!"); }
function deletePic(obj,picurl) {
var xhrD = new XMLHttpRequest();
xhrD.open("get", "ImgDelete.aspx?f=" + picurl, true);
xhrD.onload = function () {
obj.parentElement.remove();
}
xhrD.onerror = function () { }
xhrD.send();
}
</script>
</form>
</body>
</html>
二、后台代码
后台包含两个页面一个是上传页面,一个是删除页面。
1.上传页面
上传页面名称为“ImgUp.aspx”,前台页面删除所有html代码,只保留一行如下:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ImgUp.aspx.cs" Inherits="PicUpload.ImgUp" %>
后台主要代码如下:
protected void Page_Load(object sender, EventArgs e)
{
string savePath = Server.MapPath(".");
int piccount = HttpContext.Current.Request.Files.Count;
ArrayList result = new ArrayList();
if (piccount == 0)
{
Response.Write("1");
Response.End();
}
for (int i = 0; i < piccount; i++)
{
HttpPostedFile file = HttpContext.Current.Request.Files[i];
string filename = DateTime.Now.ToString("yyyyMMddmmssfff") + i.ToString() + System.IO.Path.GetExtension(file.FileName);
file.SaveAs(savePath + "\\" + filename);
result.Add(filename);
}
string rs = string.Join(",", (string[])result.ToArray(typeof(string)));
Response.Write(rs);
}
2.删除页面
上传页面名称为“ImgDelete.aspx”,前台页面删除所有html代码,只保留一行如下:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ImgDelete.aspx.cs" Inherits="PicUpload.ImgDelete" %>
后台主要代码如下:
protected void Page_Load(object sender, EventArgs e)
{
string filename = HttpContext.Current.Request["f"];
string FileUrl = Server.MapPath(filename);
if (File.Exists(FileUrl))
{
File.Delete(FileUrl);
}
}
三、代码
以上步骤我们图片上传的基本框架已实现,需要的朋友可以进行完善。代码下载请单击。