有时候我们需要上传图片时不刷新页面,那么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+IW9UJCrqhh1dRQ44OoMx2osYNWBBELi9UL7VPrwmKmCbnX0ZyBqUSNNdR4fiteMEFwsnAHYOsKn2h8Cs0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ScAvB6VsAv52+MxVz06oT02riFWcjl/807995E6btGPVe8rDRisdGK4aMVjz29ophr4yd9OG4Nzw9Up+HN8vjRMlaE2C+PrmHD4uS2jArYtaksOny+VODZ08KnBHy7qcfjJkW/M4U2VuTxo+aEDAy5N2RH4wd8f6YEZ4eqS9jm9Zd/yjAXHFePvQHHxYl8EcFRAl4HSBKwOsAUQJeB4gS8DpAlIDX4cOiBI/OHxUfFiV4dAYPsEOIBDw6Qrk5+cVHsuJdGD0GAR8WJXh0nHOK8+i4+GmapuRy+WAKEIcPixI8Orxj8R4dIVFahzKw3RQS4MOiBI9Ovz062Ejmr6NPOwR4dAQBj47zitRxzbVHBxPJXluAR6e/gEfHfqX/Hh0mgJ1AxJPS6QLYIayARwd3xq0TG8nf385/sIIoRQIeHXsmNz062EgWmLGDR0ck4NHhZxft0RF6G8tcdC1K8OgIAh6dwQM8OiIBj86gAR4dsYBHZzAAjw4AIBAl4IWAKAGvA0QJeB0gSsDrAFECXocPixI8On9UfFiU4NEZPMAOIRLw6DiNEzt48XfERGI3hIAoRQAeHe4wBAcv7o5o3H+u4xl8WJT+69Hhb9wUHrwbd8TC0yYdHxal/3p0sLuJsdnF3xF3QODR6Sf+69Fhb7S1jwSb3Y07sneLW1GCR0c0fuzR4T2V7BuHpXtS8iUFdgiR+K9Hh9+Nfe2BndNF3hG/T6HHN4jSJf7r0WHBcytis4u6Ixr3n+uAR8dd/Nijg39LiRu8G3eEeXMKHh13AY/O4AEeHZGAR2fQAI+OWMCjMxiARwcAEIgS8EJAlIDX8X9F1qKFlXKFzAAAAABJRU5ErkJggg==" alt="" />

使用Ajax上传图片到服务器(不刷新页面)的更多相关文章

  1. ajax上传图片到服务器

    通过Ajax方式上传文件,使用FormData进行Ajax请求.上传文件或图片时,要求的格式为enctype ="multipart/form-data"(以二进制格式上传),在使 ...

  2. js ajax上传图片到服务器

    $("#up_goods_pic").on('change',function(){ var file = this.files[0]; var url = webkitURL.c ...

  3. 确认框的使用。弹出一个确认框,Ajax提交一个请求,刷新页面。

    视图: <td> @if (item.ReviewProject.DeclareState == DeclareOrReviewState.正在进行 && !item.Is ...

  4. ajax上传图片到服务器简单操作

    前端: 通过Ajax方式上传文件,使用FormData进行Ajax请求.上传文件或图片时,要求的格式为enctype ="multipart/form-data"(以二进制格式上传 ...

  5. Ajax请求数据与删除数据后刷新页面

    1.ajax异步请求数据后填入模态框 请求数据的按钮(HTML) <a class="queryA" href="javascript:void(0)" ...

  6. 使用ajax和history.pushState无刷新改变页面URL onpopstate(转)

    Javascript代码 var htmlData1 = $.ajax(    {    url: "/getXXXResponse",    async: false }).re ...

  7. 基于jQuery的ajax系列之用FormData实现页面无刷新上传

    接着上一篇ajax系列之用jQuery的ajax方法向服务器发出get和post请求写,这篇主要写如何利用ajax和FormData实现页面无刷新的文件上传效果,主要用到了jQuery的ajax()方 ...

  8. Ajax回退刷新页面问题的解决办法

    在脚本之家看到一篇文章,觉得以后可能会用上,但是竟然不能收藏,所以只能将其转到博客园. 以下是原文地址: http://www.jb51.net/article/87856.htm   这篇文章主要介 ...

  9. Ajax异步调用http接口后刷新页面

    使用Ajax的目的就是提高页面响应速度,无需同步调用,无需整个页面刷新.这里直接在html中使用js来实现: 先获取XMLHttpRequest对象 var xmlHttp; //创建一个xmlHtt ...

随机推荐

  1. 用SQLite查看编辑android导出的微信聊天记录

    上一篇我们已经能够完成文字版微信聊天记录导出android了,也即复制或剪切MicroMsg.db文件到电脑,以.db格式结尾的文件是数据库文件(database document),需要安装相关数据 ...

  2. 我的Java书单之优秀的入门书

    我始终相信,学习任何一门新技术,该技术相关的优秀书籍总是最好的资料.当然了,优秀的视频教程能帮组你快速地了解该技术,但是要深入和系统地去学习该技术,好的书籍就显得尤为重要了.结合我自己学习java的经 ...

  3. python 深入模块和包

    模块可以包含可执行语句以及函数的定义. 这些语句通常用于初始化模块. 它们只在 第一次 导入时执行.只在第一次导入的时候执行,第一次.妈蛋的第一次...后面再次导入就不执行了. [1](如果文件以脚本 ...

  4. UnsupportedClassVersionError: Bad version number in .class file

    java.lang.UnsupportedClassVersionError: Bad version number in .class file造成这种过错是ni的支撑Tomcat运行的JDK版本与 ...

  5. PYTHON 自动化之路 (二)

    一.python 模块的使用 模块的使用: import os #调用 os 模块 cmd_s = os.popen("dir").read() #打开路径为结果保存为cmd_sp ...

  6. hiho #1223 不等式

    #1223 : 不等式 时间限制:10000ms 单点时限:1000ms 内存限制:256MB 描述 给定n个关于X的不等式,问最多有多少个成立. 每个不等式为如下的形式之一: X < C X ...

  7. Android列表控件ListView详解

    ListView绝对可以称得上是Android中最常用的控件之一,几乎所有应用程序都会用到它. 由于手机屏幕空间都比较有限,能够一次性在屏幕上显示的内容并不多,当我们的程序中有大量的数据需要展示的时候 ...

  8. COGS 2479 偏序 题解

    [题意] 给定一个有n个元素的序列,元素编号为1~n,每个元素有三个属性a,b,c,求序列中满足i<j且ai<aj且bi<bj且ci<cj的数对(i,j)的个数. 对于30%的 ...

  9. 1个简单的Log

    #pragma once #include <windows.h> #include <process.h> class CLogger { public: static CR ...

  10. MD5 加密字符串

    public class MD5 { /*** * MD5加码 生成32位md5码 */ public static String string2MD5(String inStr){ MessageD ...