ajax无刷新上传
我们在使用上传控件的时候,会遇到刷新的问题,最近使用ajax做的上传,觉得效果还是很不错。
首先,我们需要在页面上放上上传控件;需要注意的是,我们必须放在form里面,实现表单上传。
选择图片:<input type="file" class="file" name="picture" /><br />
</form>
前台提交方法
function TajaxFileUpload() {
var mypath = "../ajax/upload.ashx?fileName="+需要的参数;
$("form[name='uploadPic']").ajaxSubmit({
url: mypath,
type: 'POST',
success: function (html, status) {
if (status == "success") {
html = html.replace(/<\/?[^>]*>/g, '');
//html = html.replace(/[ | ]*\n/g, '\n');
var json = eval('(' + html + ')');
if (json.state == "success") {
//上传成功
}
else {//上传失败
}
}
else {
art.dialog.alert("请求数据失败");
} //stauts success
} //submit success
}); //ajaxSubmit
} //t ajax
upload.ashx代码如下
using System;
using System.IO;
using System.Web;
using System.Text;
using System.Net; namespace BatchImageUpload
{
/// <summary>
/// Summary description for upload
/// </summary>
public class upload : IHttpHandler
{ public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
try
{
if (context.Request.Files["picture"] == null)
{
//图片控件中没有选择图片
context.Response.Write("{state:'error',msg:'您还未选择图片'}");
}
else
{ string fileName = context.Request.QueryString["fileName"];
HttpPostedFile pic = context.Request.Files["picture"];
string foldPath = HttpContext.Current.Server.MapPath("/") + @"OrderUserInfoImages\";
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 = GetImageName() + 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 = 0; i < allowExt.Length; i++)
{
if (string.Compare(allowExt[i], _ImageExt, true) == 0)
{ 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(0, 999999).ToString());
return serial.ToString(); } #endregion public bool IsReusable
{
get
{
return false;
}
}
}
}
单文件上传只需要按照这个方法就可以。如果要做到批量上传,需要动态添加上传控件,然后遍历上传控件坐上传功能即可
ajax无刷新上传的更多相关文章
- 移动端图片上传解决方案localResizeIMG先压缩后ajax无刷新上传
现在科技太发达,移动设备像素越来越高,随便一张照片2M+,但是要做移动端图片上传和pc上略有不同,移动端你不能去限制图片大小,让用户先处理图片再上传,这样不现实.所以理解的解决方案就是在上传先进行图片 ...
- ajaxfileupload.js插件结合一般处理文件实现Ajax无刷新上传
先上几张图更直观展示一下要实现的功能.本功能主要通过Jquery ajaxfileupload.js插件结合ajaxUpFile.ashx一般应用程序处理文件实现Ajax无刷新上传功能,结合NPOI2 ...
- ajax无刷新上传和下载
关于ajax无刷新上传和下载 这是一个没什么含量但是又用的比较多又不得不说的问题,其实真的不想说,因为没什么好说的. 关于上传 1.使用Flash,ActiveX 上传 ,略... 2.自己写XMLH ...
- ajax 无刷新上传
最近要做微信的图文上传,因为一个图文了表中可以有多个图文,所有按钮需要随时添加,所以做了一种无刷新上传的方法. 首先我们要在html页面中写上这样的几段代码 javascript: $(functio ...
- Ajax 无刷新上传文件插件 uploadify 的使用
在表单中无法直接使用 Ajax 上传文件,解决的思路可以是使用插件无刷新地上传文件,返回文件上传后的地址,然后把该地址作为 Ajax 的参数传递给服务器端进行数据库处理.可以使用 uploadify ...
- ajax无刷新上传文件
网页上传文件最简单的方式就是通过表单上传了,但是在提交表单的时候会导致网页刷新,但有的时候我们不想网页刷新,有什么办法呢,我们可以使用ajax上传文件来做到这一点.只有ajax还不行,还需要JavaS ...
- jquery 的ajax无刷新上传文件之后,页面还是会莫名的刷新-----解决办法
文件上传用到全局数组: $_FILES 只需要把下面的 <button onclick="post()">提交</button> 改为 <input ...
- jQuery.form Ajax无刷新上传错误 (jQuery.handleError is not a function) 解决方案
今天,随着ajaxfileupload时间firebug财报显示,"jQuery.handleError is not a function"错误.因为一旦使用jQuery.for ...
- jquery ajax 无刷新上传
var form = new FormData(); form.append('file', $("#submitmaterials").find("input" ...
随机推荐
- flyway 管理数据库版本
Flyway 和 Liquibase 都是 Java 项目中常用的 DB migration 工具, 从使用简便性看,Flyway 比 Liquibase 更简单, 从 github 的 star 数 ...
- JAVA大数——lightoj1024
要用 System.gc() 清理内存 类必须命名成Main,一些大整数的操作 import java.math.BigInteger; import java.util.Scanner; publi ...
- 强大的pdf文件操作小工具——PDFtk的小白用法 【转载】
转载出处https://www.cnblogs.com/basterdaidai/p/6204518.html 前言 作为程序员,大家都知道的,总是会被技术小白问各种跟编程没什么关系的硬件.软件问题. ...
- 隐藏tomcat页面异常显示的版本信息
1.正常情况下,tomcat遇到404或500会返回版本信息: 2.有时我们不需要暴露版本信息,像这样: 3.只需要修改apache-tomcat-7.0.59的lib目录下的catalina.jar ...
- centos7.5下coredns+etcd搭建DNS服务器
coredns简介 安装etcd 安装coredns 设置域名解析 A记录 AAAA记录 CNAME记录 SRV记录 TXT记录 coredns简介 CoreDNS是一个DNS服务器,和Caddy S ...
- How to Add Swap on CentOS
About Linux Swapping Linux RAM is composed of chunks of memory called pages. To free up pages of RAM ...
- PAT_A1106#Lowest Price in Supply Chain
Source: PAT A1106 Lowest Price in Supply Chain (25 分) Description: A supply chain is a network of re ...
- java 数组中的数值反转输出
package com.test; /** *数组元素反转 * */ public class ArraySwap { public static void main(String[] args) { ...
- K8S之部署Dashboard
转载声明 本文转载自:ASP.NET Core on K8S深入学习(2)部署过程解析与部署Dashboard 1.Yaml安装 下载yaml文件 wget https://raw.githubuse ...
- Win10下使用默认的照片查看器
在打开图片的时候默认是 画图,我们想要用windows图片器打开,但是更多应用里面没有这一选项, 按 Windows徽标键+R键,打开运行命令窗口,输入"regedit"命令 来打 ...