当前位置: 首页 > 图文教程 > 网络编程 > Javascript > jquery 批量上传图片实现代码

Javascript
jQuery生成asp.net服务器控件的代码
javascript 实现的完全兼容鼠标滚轴缩放图片的代码
JavaScript学习笔记(十七)js 优化
使用SyntaxHighlighter实现HTML高亮显示代码的方法
javascript contains和compareDocumentPosition 方法来确定是否HTML节点间的关系
利用jQuery 实现GridView异步排序、分页的代码
jquery.lazyload 实现图片延迟加载jquery插件
Lazy Load 延迟加载图片的 jQuery 插件
jquery 插件实现图片延迟加载效果代码
javascript小数计算出现近似值的解决办法
jquery1.4后 jqDrag 拖动 不可用
jquery 应用代码 方便的排序功能
选择TreeView控件的树状数据节点的JS方法(jquery)
jquery 图片Silhouette Fadeins渐显效果
JQuery Dialog(JS 模态窗口,可拖拽的DIV)
javascript 同时在IE和FireFox获取KeyCode的代码
js 键盘记录实现(兼容FireFox和IE)
javascript 函数速查表
jQuery AnythingSlider滑动效果插件
经典海量jQuery插件 大家可以收藏一下

Javascript 中的 jquery 批量上传图片实现代码


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2010-02-27   浏览: 170 ::
收藏到网摘: n/a

在网上一直找不到jquery上传图片的例子,今天由于工作需要,在网上找了很长时间,找到了一个不太完整的例子,自已又对其进行了修改,现在已经可以使用,但只限于IE,火狐下不能使用,因为火狐下得不到本地上传的图片路径,希望能对新手有所帮助. 前台: upload.htm
复制代码 代码如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>upload</title>
<link href="upload.css" rel="Stylesheet" />
</head>
<body>
<form>
<ul>
<li>
<button id="SubUpload" onclick="TSubmitUploadImageFile();return false;">
确定上传</button>
<button id="CancelUpload" class="ManagerButton" onclick="javascript:history.go(-1);">
取消</button>
<button id="AddUpload" class="ManagerButton" onclick="TAddFileUpload();return false;">
增加</button>
</li>
</ul>
<ul id="loadimage">
<li>
<div class="imagelabel">
图片1:</div>
<div class="imagepath">
<input name="" size="45" id="uploadImg1" type="file" /></div>
<div class="loadinfo">
<span id="uploadImgState1"></span>
</div>
</li>
</ul>
</form>
</body>
</html>
<script type="text/javascript" src="http://www.cnblogs.com/JS/jquery-1.3.2-vsdoc.js"></script>
<script type="text/javascript">
var TfileUploadNum = 1; //记录图片选择框个数
var Tnum = 1; //ajax上传图片时索引
//增加上传按钮
function TAddFileUpload() {
var idnum = TfileUploadNum + 1;
var str = "<li>";
str += "<div class='imagelabel'>图片" + idnum + ":</div>";
str += "<div class='imagepath'><input name='' size='45' id='uploadImg" + idnum + "' type='file' /></div>";
str += "<div class='loadinfo'><span id='uploadImgState" + idnum + "'></span></div>";
str += "</li>";
$("#loadimage").append(str);
TfileUploadNum += 1;
}
//开始上传
function TSubmitUploadImageFile() {
document.getElementById("SubUpload").disabled = true;
document.getElementById("CancelUpload").disabled = true;
document.getElementById("AddUpload").disabled = true;
setTimeout("TajaxFileUpload()", 1000); //此为关键代码
}
//Ajax上传方法
function TajaxFileUpload() {
if (Tnum < TfileUploadNum + 1) {
//准备提交处理
$("#uploadImgState" + Tnum).html("<img src='/gif/upfileloader.gif'/>");
//开始提交
$.ajax({
type: "POST",
url: "Handler.ashx",
data: { upfile: $("#uploadImg" + Tnum).val()},
success: function(data, status) {
var stringArray = data.split("|");
//stringArray[0]    成功状态(1为成功,0为失败)
//stringArray[1]    上传成功的文件名
//stringArray[2]    消息提示
if (stringArray[0] == "1") {
//上传成功
$("#uploadImgState" + Tnum).html("<img src='/gif/Success.gif' />" + stringArray[1] + "--" + stringArray[2]);
}
else {
//上传出错
$("#uploadImgState" + Tnum).html("<img src='/gif/Error.gif' />" + stringArray[1] + "--" + stringArray[2]);
}
Tnum++;
setTimeout("TajaxFileUpload()", 1000);
}
});
}
else {
document.getElementById("SubUpload").disabled = false;
document.getElementById("CancelUpload").disabled = false;
document.getElementById("AddUpload").disabled = false;
}
}        
</script>

处理程序Handler.ashx
复制代码 代码如下:

<%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
using System.IO;
using System.Text;
using System.Net;
public class Handler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
//源图片路径
string _fileNamePath = "";
try
{
_fileNamePath = context.Request.Form["upfile"];
string _savedFileResult = UpLoadFile(_fileNamePath); //开始上传
context.Response.Write(_savedFileResult);//返回上传结果
}
catch
{
context.Response.Write("0|error|文件路径错误");
}
}
/// <summary>
/// 保存图片
/// </summary>
/// <param name="fileNamePath"></param>
/// <returns></returns>
private string UpLoadFile(string fileNamePath)
{
//图片格式
string fileNameExt = fileNamePath.Substring(fileNamePath.IndexOf('.')).ToLower();
if (!CheckFileExt(fileNameExt)) return "0|error|图片格式不正确!";
//保存路径
string toFilePath = "ProductUpload/";
//物理完整路径
string toFileFullPath = HttpContext.Current.Server.MapPath(toFilePath);
//检查是否有该路径 没有就创建
if (!Directory.Exists(toFileFullPath))
{
Directory.CreateDirectory(toFileFullPath);
}
//生成将要保存的随机文件名
string toFileName = GetFileName();
//将要保存的完整路径
string saveFile=toFileFullPath +toFileName + fileNameExt;
///创建WebClient实例
WebClient myWebClient = new WebClient();
//设定windows网络安全认证
myWebClient.Credentials = CredentialCache.DefaultCredentials;
//要上传的文件
FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read);      
BinaryReader r = new BinaryReader(fs);
//使用UploadFile方法可以用下面的格式
myWebClient.UploadFile(saveFile,fileNamePath);
return "1|"+toFileName+fileNameExt+"|保存成功.";
}
/// <summary>
/// 检测图片类型
/// </summary>
/// <param name="_fileExt"></param>
/// <returns>正确返回True</returns>
private bool CheckFileExt(string _fileExt)
{
string[] allowExt = new string[] { ".gif", ".jpg", ".jpeg" };
for (int i = 0; i < allowExt.Length; i++)
{
if (allowExt[i] == _fileExt) { return true; }
}
return false;
}
/// <summary>
/// 得到随机图片名
/// </summary>
/// <returns></returns>
public static string GetFileName()
{
Random rd = new Random();
StringBuilder serial = new StringBuilder();
serial.Append(DateTime.Now.ToString("yyMMddHHmmssff"));
serial.Append(rd.Next(0, 9999).ToString());
return serial.ToString();
}
public bool IsReusable
{
get
{
return false;
}
}
}

CSS样式 upload.css
复制代码 代码如下:

body{font-size: 12pt;}
ul{list-style: none;}
li{margin: 0px;}
#loadimage{width: 860px;overflow: hidden;}
.imagelabel{ float: left; width: 60px; height: 25px;}
.imagepath{float: left; width: 400px; height: 25px; }
.loadinfo{float: left; width: 400px;height: 25px;}