StringBuilder serial = new StringBuilder();
serial.Append(DateTime.Now.ToString("yyyyMMddHHmmssff"));
serial.Append(rd.Next(0, 999999).ToString());
return serial.ToString();
即使我命名精确到毫秒,另外再加上随机数,可是还是有上传的第二张图片把上传的第一张图片覆盖的情况出现。所以此处我设置了延时1秒后在上传下一张图片。刚开始做这个东西的时候,用的是for循环,来把所有的图片一个一个的循环地用ajax上传,可是for循环速度太快了,可能第一张图片还没来得及ajax,第二张就被for过来了,还是有第二张覆盖第一张的情况出现。
下面来看TajaxFileUpload()函数,代码如下:
function TajaxFileUpload()
{
if(Tnum<TfileUploadNum+1)
{
//准备提交处理
("#uploadImgState"+Tnum).html("<img src=../images/loading.gif />");
//开始提交
.ajax
({
type: "POST",
url:"http://localhost/ajaxText2/Handler1.ashx",
data:{upfile:("#uploadImg"+Tnum).val(),category:("#pcategory").val()},
success:function (data, status)
{
//alert(data);
var stringArray = data.split("|");
if(stringArray[0]=="1")
{
//stringArray[0] 成功状态(1为成功,0为失败)
//stringArray[1] 上传成功的文件名
//stringArray[2] 消息提示
("#uploadImgState"+Tnum).html("<img src=../images/note_ok.gif />");//+stringArray[1]+"|"+stringArray[2]);
}
else
{
//上传出错
("#uploadImgState"+Tnum).html("<img src=../images/note_error.gif />"+stringArray[2]);//+stringArray[2]+"");
}
Tnum++;
setTimeout("TSubmitUploadImageFile()",0);
}
});
}
}
上面的代码没什么可说的,很容易看懂。下面来看Handler1.ashx(一般处理程序)如何来处理post过来的图片的(此代码来自网上,具体地址忘记了),下面只给出关键代码,全部代码在附件里。
1、
string _fileNamePath = "";
try
{
_fileNamePath = context.Request.Form["upfile"];
//开始上传
string _savedFileResult = UpLoadFile(_fileNamePath);
context.Response.Write(_savedFileResult);
}
catch
{
context.Response.Write("0|error|上传提交出错");
}
2、
//生成将要保存的随机文件名
string fileName = GetFileName() + fileNameExt;
//物理完整路径
string toFileFullPath = HttpContext.Current.Server.MapPath(toFilePath);
//检查是否有该路径 没有就创建
if (!Directory.Exists(toFileFullPath))
{
Directory.CreateDirectory(toFileFullPath);
}
///创建WebClient实例
WebClient myWebClient = new WebClient();
//设定windows网络安全认证 方法1
myWebClient.Credentials = CredentialCache.DefaultCredentials;
//要上传的文件
FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read);
//FileStream fs = OpenFile();
BinaryReader r = new BinaryReader(fs);









