有时候我们需要上传图片时不刷新页面,那么Ajax就是很好的东西哦。之前在网上找了很多的资料都不对,不是这里就是那里错,这是本人亲自测试了的哈,是没有问题的,若有不足之处希望指正。我用的.net,对了这里还需要引用Jquery跟Jquery.form.js两个文件,没看到上传附件在哪里咯,需要的朋友可以给我留言哈
前台代码 Default2.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %> <!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></title>
<script src="admin/js/jquery.js" type="text/javascript"></script>
<script src="admin/js/jquery.form.js" type="text/javascript"></script>
<script type="text/javascript">
function TajaxFileUpload() {
var imgname = $.trim($("#File1").val());
if (imgname != "") {
$("#form1").ajaxSubmit({
success: function (html, status) {
if (status == "success") {
var json = eval('(' + html + ')');
if (json.state == "success") { //上传成功
alert("上传成功!");
}
else {
alert(json.msg + "上传失败!");
}
}
},
error: function (error) {
alert(error);
},
url: 'admin/ajax/upload.ashx', /*设置post提交到的页面*/
type: "post", /*设置表单以post方法提交*/
dataType: "text" /*设置返回值类型为文本*/
});
}
else {
alert("请上传图片!");
return false;
}
} </script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="File1" type="file" name="picture" />
<input type="button" value="上 传" onclick="TajaxFileUpload()" />
</div>
</form>
</body>
</html>
Ajax页面代码 upload.ashx
<%@ WebHandler Language="C#" Class="upload" %> using System;
using System.Web;
using System.IO;
using System.Text;
using System.Net; public class upload : IHttpHandler
{ public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
try
{
string time = DateTime.Now.ToString("yyyyMMdd").Trim();
string fileName = time; HttpPostedFile pic = context.Request.Files["picture"];
string foldPath = HttpContext.Current.Server.MapPath("~/UploadFile/") + fileName+"\\";
//foldPath = foldPath + fileName;
DirectoryInfo di = new DirectoryInfo(foldPath);
if (!di.Exists)//如果文件夹目录不存在
{
di.Create();//新建文件夹
}
string imageName = UpLoadImage(pic, foldPath);
context.Response.Write("{state:'success',msg:'上传成功:" + imageName + "'}"); }
catch (Exception ex)
{
context.Response.Write("{state:'error',msg:'" + ex.Message + "'}");
}
}
#region 上传图片
/// <summary>
/// 上传图片
/// </summary>
/// <param name="imgfile">文件http流</param>
/// <param name="nowpath">所需放置的文件路径</param>
/// <returns>上传成功,返回字符串,否则,抛出异常</returns>
public static string UpLoadImage(HttpPostedFile imgfile, string nowpath)
{
try
{
string serverPath = System.Web.HttpContext.Current.Server.MapPath("~"); string toFilePath = Path.Combine(serverPath, nowpath); //获取要保存的文件信息
FileInfo file = new FileInfo(imgfile.FileName);
//获得文件扩展名
string fileNameExt = file.Extension; //验证合法的文件
if (CheckImageExt(fileNameExt))
{
//生成将要保存的随机文件名
string fileName = DateTime.Now.ToString("yyyyMMddHHmmss").Trim() + fileNameExt; //获得要保存的文件路径
string serverFileName = toFilePath +fileName;
//物理完整路径
string toFileFullPath = serverFileName; //HttpContext.Current.Server.MapPath(toFilePath); //将要保存的完整文件名
string toFile = toFileFullPath;//+ fileName; ///创建WebClient实例
WebClient myWebClient = new WebClient();
//设定windows网络安全认证 方法1
myWebClient.Credentials = CredentialCache.DefaultCredentials;
////设定windows网络安全认证 方法2
imgfile.SaveAs(toFile); string relativePath = fileName;
return relativePath;
}
else
{
throw new Exception("文件格式非法,请上传gif|jpg|bmp|png格式的文件。");
}
}
catch
{
throw;
}
}
#endregion #region 图片上传格式和文件名
/// <summary>
/// 检查是否为合法的上传图片
/// </summary>
/// <param name="_fileExt"></param>
/// <returns></returns>
public static bool CheckImageExt(string _ImageExt)
{
string[] allowExt = new string[] { ".gif", ".jpg", ".jpeg", ".bmp", ".png" };
for (int i = ; i < allowExt.Length; i++)
{
if (string.Compare(allowExt[i], _ImageExt, true) == )
{ return true; }
}
return false; }
private static string GetImageName()
{
Random rd = new Random();
StringBuilder serial = new StringBuilder();
serial.Append(DateTime.Now.ToString("yyyyMMddHHmmssff"));
serial.Append(rd.Next(, ).ToString());
return serial.ToString(); } #endregion public bool IsReusable
{
get
{
return false;
}
} }
最后上传的图片的保存路径效果图如下:
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAANwAAABoCAIAAAAVYwm1AAAOrUlEQVR4nO2de1QTVx7H54/9Y//o6e7Zbm172m1tbd3T56m1tlYtkkLboFWrba2uWhUXRfqwesalWh8oiASQIBZXcCygiAgokYfWqsS3W0EQiErVMKCU8khCFOVhEu/+kWQyM7kTJjCSpPl9zj3HmTu/e393Tr7MvZnc75FAAOBlEJ4eAADwAVECXgeIEvA6BipKs+X+sRr9D4caYwq0/ll+ONR4rEZvttyX5PMA0MBFWVLRVlqpazKYbvcg/yxNBlNppa6kok2SzwNAAxdlvKpef9ei70K6u35a9F1If9cSr6qX5PMA0MBFGVOgvdWD2u/4dbnVg2IKtJJ8HgCSRJTGbtRYf7UgW8kuDdcvtXaiB1nUEQRZOMBODpJEMFWBvXSJkhFy5SVRiYzdIEopkUCUHd2oIFt5tSaz25jfbczvNeSY2jPysjY1XL/UchuJK+rFhDxJw6rRUIHBVEUfTcj9YvsXKKUkYctCJwUTDoKpCg0VaBtS34k6QJSSIoEoDV0of2dSl2EPo0hLyzaTZumeHxW70mIzflifnrzmv4krt8RFNt9GAkW9mJBv0rBqNFRgMHVeMN7ahCxwFSCilJKELQu9KZhYXNrPRIYuEKWU4EWpVqvj4uLEtI8p0OrvotzMhK62TKsi77dsQ1dXIs0iXtkSF9lkRAJFHU7IE2pZNbXU+CDqf4Lx1iZknqsAEaWEJGxZ6IQgIrykn4n0d0GUUoIR5bFjx15++eXhw4eLaR9ToG2/g3ZTcZ3N6VZFHi5IOFyQcCgvvjgnrnBXbF5GdE76uqzUtTs2r0pLWpmasGJLXGRjB+IW9UJCrqhh1dRQ44OoMx2osYNWBBELi9UL7VPrwmKmCbnX0ZyBqUSNNdR4fiteMEFwsnAHYOsKn2h8Cs0Et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