ASP net图片上传预览及无刷新上传
网页中图像无自动刷新实现方法
![网页中图像无自动刷新实现方法](https://img.taocdn.com/s3/m/f71a5b8284868762caaed56b.png)
}
string MakeValidateCode()
{
char[] s = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z','A','B', 'C','D','E','F','G','H','I','J','K','L','M','N','P','Q','I','S','T','U','V', 'W','X','Y','Z'};//枚举数组
ASP.NETMVC文件上传教程(二)
![ASP.NETMVC文件上传教程(二)](https://img.taocdn.com/s3/m/243e683a0166f5335a8102d276a20029bd6463aa.png)
MVC⽂件上传教程(⼆)上⽂我们讲了简单的上传以及需要注意的地⽅,查相关资料时,感觉上传⾥⾯涉及到的内容还是⽐较多,于是就将上传这⼀块分为⼏节来处理,同时后续也会讲到关于做上传时遗漏的C#应该注意的地⽅,及时进⾏查漏补缺,尽量将这⼀块完善起来。
引⼊上⼀节我们讲到了上传这⼀块,有朋友提出未涉及到⼤⽂件的上传这⼀块,思前想后还是来试着做做,毕竟之前没怎么去仔细考虑过这个问题,尤其还可以联系实际开发中创建⽂件夹等⼀系列问题,同时关于上传在⽹上随便找找都充斥着⼤量的组件,我们何必再去造轮⼦,我需要做的是只是对基础的回顾以及进⼀步深⼊以及在做的过程中发现⼀些细节性的问题并解决就⾜矣,不喜勿喷。
深⼊上传再次声明对于上传可以显⽰上传进度之类我们不去做过多探讨,有这样的组件,⾃⾏去找,我们只需实现⽐较核⼼的这⼀块即可。
我们可以想象这⼀样⼀个场景:⽐如在博客园中,每个博客者都可以上传⽂件如图⽚、脚本之类,我们可以通过园友名称来创建每个园友上传的⽂件,接下来我们来实现这样的⼀个场景。
既然是对应博客的名称创建⽂件,也就是需要对应的博客这样的⼀个类。
如下:public class BlogSample{public string UserName { get; set; }public string Id { get; set; }}我们通过博客名称来创建⽂件夹并在该⽂件夹下以唯⼀的Id来创建⼦⽂件夹,在该Id⽂件夹下的附件( atttachment )中存储上传的⽂件。
接下来我们需要梳理整个上传⽂件的过程。
难道就把要上传的⽂件直接到上传到对应的⽂件夹吗,这么做显然不是最优的,当有上传中断时则在⽂件夹创建的⽂件不是完整的则是垃圾⽂件,⽽我们直接先创建⼀个临时⽂件,即使上传失败我们可以定期清理临时⽂件也就是垃圾⽂件,若未中断,上传完毕时则将临时⽂件移动到我们对应的⽂件夹中。
通过我们实际下载⽂件时很明显看的出也是这么做的。
asp.net中图片的上传和删除(全文5篇)
![asp.net中图片的上传和删除(全文5篇)](https://img.taocdn.com/s3/m/6fa2d10166ec102de2bd960590c69ec3d4bbdb62.png)
中图片的上传和删除(全文5篇)第一篇:中图片的上传和删除中图片的上传和删除上传图片: bool fileIsValid = false;//获取上传文件的后缀String fileExtension = System.IO.Path.GetExtension(this.file.FileName).ToLower();String[] restrictExtension ={ “.gif”, “.jpg”, “.bmp” };//判断文件类型是否符合要求for(int i = 0;i < restrictExtension.Length;i++){if(fileExtension == restrictExtension[i]){fileIsValid = true;}}//如果文件类型符合要求,调用SaveAs方法实现上传,并显示相关信息if(fileIsValid == true){this.file.SaveAs(Server.MapPath(“~/文件夹名/”)+ file.FileName);}删除图片://///// 删除文件或图片//////当前文件的路径/// 是否删除成功public static bool FilePicDelete(string path){bool ret = false;System.IO.FileInfo file = new System.IO.FileInfo(path);if(file.Exists){file.Delete();ret = true;}return ret;}第二篇: 删除数据学习资料删除数据protected void Button2_Click(object sender, EventArgs e){SqlConnection conn = newSqlConnection(ConfigurationManager.ConnectionStrings[“newsConnectionString”].ConnectionString);SqlCommand cmd = new SqlCommand();mandText=“delete from login where 编号='”+this.TextBox1.Text+“'”;cmd.Connection=conn;conn.Open();cmd.ExecuteNonQuery();conn.Close();Response.Write(“”);Response.Redirect(“Default.aspx”);}第三篇: 图片上传学习课件后台代码protected void Page_Load(object sender, EventArgs e){this.Image1.Visible = false;}protected void Button1_Click(object sender, EventArgs e){string fullfilename = this.File1.PostedFile.FileName;string filename = fullfilename.Substring(stIndexOf(“”)+ 1);string type = fullfilename.Substring(stIndexOf(“.”)+ 1);if(type == “jpg” || type == “bmp” || type == “gif”){this.File1.PostedFile.SaveAs(Server.MapPath(“WebSite11”) + “” + filename);this.Image1.ImageUrl = “WebSite11/” + filename;this.Image1.Visible = true;}else{Response.Write(“”);}}第四篇:幼教考察报告-定稿删除图片安居区幼儿教育考察报告考察概况2009年5月21、22日和6月8、9日,安居区教育局幼教考察团在局党组成员、副局长艾勇的带领下,先后奔赴巴中市南江县和成都市新津县,实地考察了两县的幼儿教育,通过考察,我们深切的感受到,这两处地市虽然办园机制各不相同,但具有鲜明的共性:办园体制灵活、规模宏大、政府重视、特色鲜明,善于调动各方面的办园积极性,努力促进城乡学前教育的均衡发展,具有较高的保育办园质量。
ASP图片上传
![ASP图片上传](https://img.taocdn.com/s3/m/0e02cc29854769eae009581b6bd97f192279bfa6.png)
ASP图片上传一个图片上传ASP,没有大小缩略图,也没有水印..缩略图的代码可以加,水印需要组件..<%ExtName = "jpg,gif,bmp" '允许扩展名SavePath = "upload" '保存路径If Right(SavePath,1)<>"/" Then SavePath=SavePath&"/" '在目录后加(/)CheckAndCreateFolder(SavePath)UpLoadAll_a = Request.TotalBytes '取得客户端全部内容If (UpLoadAll_a>0) ThenSet UploadStream_c = Server.CreateObject("ADODB.Stream") UploadStream_c.Type = 1UploadStream_c.OpenUploadStream_c.Write Request.BinaryRead(UpLoadAll_a)UploadStream_c.Position = 0FormDataAll_d = UploadStream_c.ReadCrLf_e = chrB(13)&chrB(10)FormStart_f = InStrB(FormDataAll_d,CrLf_e)FormEnd_g = InStrB(FormStart_f+1,FormDataAll_d,CrLf_e)Set FormStream_h = Server.Createobject("ADODB.Stream") FormStream_h.Type = 1FormStream_h.OpenUploadStream_c.Position = FormStart_f + 1UploadStream_c.CopyT o FormStream_h,FormEnd_g-FormStart_f-3FormStream_h.Position = 0FormStream_h.Type = 2FormStream_h.CharSet = "GB2312"FormStreamText_i = FormStream_h.ReadtextFormStream_h.CloseFileName_j = Mid(FormStreamT ext_i,InstrRev(FormStreamText_i,"\")+1,FormEn d_g)If (CheckFileExt(FileName_j,ExtName)) ThenSaveFile = Server.MapPath(SavePath & UserFaceName(right(FileName_j,3)))If Err ThenResponse.Write "文件上传: <span style=""color:red;"">文件上传出错!</span> <a href=""" &Request.ServerVariables("URL") &""">重新上传文件</a><br />"Err.ClearElseSaveFile = CheckFileExists(SaveFile)k=Instrb(FormDataAll_d,CrLf_e&CrLf_e)+4l=Instrb(k+1,FormDataAll_d,leftB(FormDataAll_d,FormStart_ f-1))-k-2FormStream_h.Type=1FormStream_h.OpenUploadStream_c.Position=k-1UploadStream_c.CopyT o FormStream_h,lFormStream_h.SaveToFile SaveFile,2SaveFileName = Mid(SaveFile,InstrRev(SaveFile,"\")+1)Saver="upload/"&SaveFileNameresponse.write "图片上传成功!请点<a href='"&saver&"' target=_blank>此处</a>预览."'response.write"<script>window.opener.document.all.fujan.value='"&Saver&"' </script>"'response.write "<script>retunpath='"&Saver&"';</script>"'response.write "<script src='/retun.js'></script>"'response.write " <script language='javascript'>window.alert('图片上传成回:"&retun_path&"');window.close();</script>"End IfElse'response.write "sgs"Response.write "文件上传:<span style='color:red;'>文件格式不正确!仅支持"&ExtName&"文件类型,</span><a href=" &Request.ServerVariables("URL") &"> 请重新上传文件</a><br />"End IfElse%><script language="Javascript"><!--function ValidInput(){if(document.upform.upfile.value==""){alert("请选择上传文件!")document.upform.upfile.focus()return false}return true}//--></script><style type="text/css"><!--body,td,th {font-size: 12px;}--></style><form action='<%= Request.ServerVariables("URL") %>' method='post' name="upform" onSubmit="return ValidInput()"enctype="multipart/form-data">文件上传:<input type='file' name='upfile' size="25"><input name="submit" type='submit' value="上传"></form><p><%End ifSet FormStream_h = Nothing'判断文件类型是否合格Function CheckFileExt(FileName,ExtName) '文件名,允许上传文件类型FileType = ExtNameFileType = Split(FileType,",")For i = 0 To Ubound(FileType)If LCase(Right(FileName,3)) = LCase(FileType(i)) thenCheckFileExt = TrueExit FunctionElseCheckFileExt = FalseEnd ifNextEnd Function'检查上传文件夹是否存在,不存在则创建文件夹Function CheckAndCreateFolder(FolderName)fldr = Server.Mappath(FolderName)Set fso = CreateObject("Scripting.FileSystemObject")If Not fso.FolderExists(fldr) Thenfso.CreateFolder(fldr)End IfSet fso = NothingEnd Function'生成文件新的文件名Function UserFaceName(FileExt)RandomizeRanNum = Int(90000*rnd)+10000UserFaceName = UserID&Year(now)&Month(now)&Day(now)&Hour(now)&Minut e(now)&Second(now)&RanNum&"."&FileExtEnd Function'检查文件是否存在,重命名存在文件Function CheckFileExists(FileName)Set fso=Server.CreateObject("Scripting.FileSystemObject") If fso.FileExists(SaveFile) Theni=1msg=TrueDo While msgCheckFileExists = Replace(SaveFile,Right(SaveFile,4),"_" & i & Right(SaveFile,4))If not fso.FileExists(CheckFileExists) Thenmsg=FalseEnd Ifi=i+1LoopElseCheckFileExists = FileName End IfSet fso=NothingEnd Function。
asp.netH5页面图片上传处理
![asp.netH5页面图片上传处理](https://img.taocdn.com/s3/m/ecfdf46b7fd5360cba1adb72.png)
H5页面上传方法1.先引用<script src="js/ajaxfileupload.js" type="text/javascript"></script>2.页面中这样写<imgsrc="<%=headsrc %>" ><input type="file" accept=".png,.jpe,.jpeg,.jpg,.gif" id="HeadPic" name="fileData"onchange="upload_pic()" class="upload_avatar_btn" />3.上传方法functionupload_pic() {$.ajaxFileUpload({url: '/handler/AjaxHandler.ashx?otype=uploadSitePIC&OID=<%=user.ID%>&OTable=B_Member&ModuleName=用户头像', //需要链接到服务器地址secureuri: false,fileElementId: 'HeadPic', //文件选择框的id属性dataType: 'json', //服务器返回的格式,可以是jsonsuccess: function (data, status) //相当于java中try语句块的用法{$("#hd_del_head_pic").val($("#hd_del_head_pic").val() + data.fid + ",");$("#hd_head_pic").val(data.fid);$("#ucenter_head_img").attr("src",decodeURIComponent(data.msg));},error: function (data, status, e) //相当于java中catch语句块的用法{msgalert(0, data.error);}});}4.后台代码接收case "uploadSitePIC":int UID = 0;UID = Convert.ToInt32(context.Session["MID"]);int OID = Convert.ToInt32(context.Request["OID"] == null ? "0" :context.Request["OID"]);stringOTable = context.Request["OTable"];stringModuleName = context.Request["ModuleName"];//编写新增方法context.Response.ContentType = "text/plain"; HttpPostedFile file = context.Request.Files["fileData"];stringwebfilepath = "";int Fid = monVoid.SiteSaveProFile(UID, OID, OTable, ModuleName, System.IO.Path.GetExtension(file.FileName).Substring(1), "fileData", ProUtil.SiteFileRoot, ProUtil.SiteWebFileRoot, ref webfilepath, context);System.Web.Script.Serialization.JavaScriptSerializerSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();XHeditorRetuJsonInfoFileModel = new XHeditorRetuJsonInfo();FileModel.err = "";FileModel.msg = webfilepath;FileModel.fid = Fid;stringstrJson = Serializer.Serialize(FileModel);context.Response.Write(strJson);break;。
ASP.NET上传图片
![ASP.NET上传图片](https://img.taocdn.com/s3/m/2a4dc1f0aef8941ea76e0551.png)
2 文件 系统存储 方式
文件系统存 储方式是指 图片 文件 以普 通文件 的方式存 储
径用 变量 u laP t pod a h代表。
S l n e t nc n qCo n ci o n=n w qCo n cin (t o n o e S l n eto s c n ): r
展 名 进行 判 断 。
中经 常需要上传 图片 ,上传 图片的方式 有很多 种 ,但无 论哪
一
()将 图片文件转 存到服务 器预先 指定 的文 件存储路 径 3
种方式都离 不开这样两 点 :图 片文件本 身的 内容 和其存储
中 ,同时将这 个存储路径 和文件名一起 存储到 数据库对 应 的
S l T p .aC a, 0);添加参数 q Db y e r hr 5) / V /
c .aa tr ” @i g ul】. le=fe a ; mdP mees【 r ma e r” Vau i n 为 :<nu p = “u mi 2 ip tye sb t t ”
理。
()fe a e的值 可 以做 一些预处 理 ,如很 多 We 1 i Nm l b程序 中都会将上传 的图片文件名修改为当前 日期 的年月 日时分秒 ; ( 下转到 1 3页) 0 作者简介 :杨亚仿 (9 4 ) 18 一 ,男 ,硕 士 ,研究 方向 :We b应 用程序 开发 和数据库技术应用。
数据表 中,方便以后 的程序读取和处理。
路 径 ,这两点对 于图片的存 取非常重要 。在现 有的 We b程序
开发 中 ,一般 有文 件系 统存储 方式 和数据库 系 统存储 方式 ,
ASP.NETCore上传文件图片上传
![ASP.NETCore上传文件图片上传](https://img.taocdn.com/s3/m/fb07351003020740be1e650e52ea551810a6c966.png)
Core上传⽂件图⽚上传在 Core 中上传⽂件vs2019 选择⽂件后,调试停⽌问题⼯具 -> 选项 -> 项⽬和解决⽅案 -> Web项⽬ -> 浏览器窗⼝关闭时停⽌调试器(s) 复选√ 去掉1、单个⽂件IFormFile2、多个⽂件的集合:IFormFileCollectionIEnumerable<IFormFile>成员列表<IFormFile>3、Postman请求 Core Controller ⽂件using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Threading.Tasks;using Microsoft.AspNetCore.Http;using Microsoft.AspNetCore.Mvc;namespace WebApplication.Controllers{public class TestController : Controller{public IActionResult Index(){return View();}/// <summary>/// from表单submit提交上传,通过IFormFile参数获取上传⽂件信息【OK】/// el-upload【获取不到参数】/// </summary>/// <param name="files"></param>/// <returns></returns>[HttpPost("upload_avatar")]public async Task<IActionResult> UploadAvatar([FromForm] List<IFormFile> files){long size = files.Sum(f => f.Length);if (files.Count < 1)return Ok(new { code = -1, msg = "没有上传⽂件", data = "" });//当前程序路径var path = Directory.GetCurrentDirectory();foreach (var formFile in files){if (formFile != null && formFile.Length > 0){var filePath = Path.GetTempFileName();var filePath1 = bine("", Path.GetRandomFileName());#region 图⽚⽂件的条件判断//没有后缀扩展名的⽂件名var currentPictureWithoutExtension = Path.GetFileNameWithoutExtension(formFile.FileName);//⽂件后缀var fileExtension = Path.GetExtension(formFile.FileName).ToUpper();//判断后缀是否是图⽚const string fileFilt = ".gif|.jpg|.jpeg|.png";if (fileExtension == null)return new JsonResult(new { code = "-1", msg = "上传的⽂件没有后缀" });if (fileFilt.IndexOf(fileExtension.ToLower(), StringComparison.Ordinal) <= -1)return new JsonResult(new { code = "-1", msg = "请上传jpg、png、gif格式的图⽚" });//判断⽂件⼤⼩long length = formFile.Length;if (length > 1024 * 1024 * 2) //2Mreturn new JsonResult(new { code = "-1", msg = "上传的⽂件不能⼤于2M" });#endregion#region 上传图⽚using (var stream = System.IO.File.Create(filePath)){await formFile.CopyToAsync(stream);}#endregion}}//return Ok();return Ok(new { count = files.Count, size });}/// <summary>/// from表单submit提交上传,通过IFormCollection参数获取上传⽂件信息【OK】/// el-upload【OK】/// </summary>/// <param name="files"></param>/// <returns></returns>[HttpPost("up_avatar")]public async Task<IActionResult> UpAvatar([FromForm] IFormCollection formCollection){var fileFolder = bine("", "wwwroot/upload");//定义图⽚数组后缀格式string[] LimitPictureType = { ".JPG", ".JPEG", ".GIF", ".PNG", ".BMP" };FormFileCollection fileCollection = (FormFileCollection)formCollection.Files;foreach (IFormFile file in fileCollection){//获取图⽚后缀是否存在数组中string currentPictureExtension = Path.GetExtension(file.FileName).ToUpper();if (LimitPictureType.Contains(currentPictureExtension)){var fileName = $"{DateTime.Now.ToString("yyyyMMddHHmmss")}{Path.GetExtension(file.FileName)}"; var filePath = bine(fileFolder, fileName);using (var stream = new FileStream(filePath, FileMode.Create)){await file.CopyToAsync(stream);}}else{//return Json(new { status = -2, message = "请上传指定格式的图⽚", data = hash });}}return Ok();}/// <summary>/// from表单submit提交上传,通过IFormFileCollection参数获取上传⽂件信息【OK】/// el-upload【获取不到参数】/// </summary>/// <param name="formCollection"></param>/// <returns></returns>[HttpPost("batch_upload_avatar")]public async Task<IActionResult> BatchUploadAvatar([FromForm] IFormFileCollection files){long size = files.Sum(f => f.Length);var fileFolder = bine("", "wwwroot/upload");if (!Directory.Exists(fileFolder))Directory.CreateDirectory(fileFolder);if (files.Count > 0){foreach (IFormFile file in files){var fileName = $"{DateTime.Now.ToString("yyyyMMddHHmmss")}{Path.GetExtension(file.FileName)}"; var filePath = bine(fileFolder, fileName);using (var stream = new FileStream(filePath, FileMode.Create)){await file.CopyToAsync(stream);}}}return Ok();}/// <summary>/// AJAX请求上传,通过Request.Form.Files获取上传⽂件信息【OK】/// el-upload【OK】/// </summary>/// <param name="files"></param>/// <returns></returns>[HttpPost("single_upload_avatar")]public async Task<IActionResult> SingleUploadAvatar(){#region 单个⽂件上传var file = Request.Form.Files[0];string fileName = string.Empty;//using (FileStream fs = System.IO.File.Create(fileName))//{// file.CopyTo(fs);// fs.Flush();//}#endregion#region 批量上传var files = Request.Form.Files;string filePhysicalPath = string.Empty;foreach (var itemFile in files){if (file.Length > 0){var fName = System.Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);//⽂件名+⽂件后缀名using (var stream = new FileStream(filePhysicalPath + fileName, FileMode.Create)){await file.CopyToAsync(stream);}}}#endregionreturn Ok();}[HttpPost("upload_base64")]public ActionResult UploadBase64(string fileBase64, string fileName) {return Ok();}}}*JavaScript ⽅式<!DOCTYPE html><html><head><meta charset="utf-8" /><title></title><script src="lib/jquery/dist/jquery.js"></script><script>$(document).ready(function () {$("#btn_fileUpload").click(function () {var fileUpload = $("#files").get(0);var files = fileUpload.files;var data = new FormData();for (var i = 0; i < files.length; i++) {data.append(files[i].name, files[i]);}$.ajax({type: "POST",url: 'http://localhost:55084/single_upload_avatar',contentType: false,processData: false,data: data,success: function (data) {console.log(JSON.stringify(data));},error: function () {console.log(JSON.stringify(data));}});});})//前端第⼀种提交⽅式function uplpadfile() {//获取表单的数据var formdatavar file = $("#files").get(0);var files = file.files;var formdata = new FormData();for (var i = 0; i < files.length; i++) {formdata.append("files", files[i]);}$.ajax({type: 'Post',data: formdata,contentType: false,processData: false,url: "http://localhost:55084/upload_avatar",success: function (result) {if (result.Success) {} else {alert('提交失败,重新尝试提交');}}})};</script></head><body><h3>1、ajax上传</h3><form enctype="multipart/form-data"><input type="file" id="files" name="files" placeholder="file" multiple><input type="button" id="btn_fileUpload" value="提交"></form><br /><br /><br /><h3>2</h3><form enctype="multipart/form-data"><input type="file" name="files" id="files" value="选择需要上传的⽂件" multiple /><input type="button" value="提交" onclick="uplpadfile()"></form><br /><br /><br /><h3>3、form 表单标签 submit 上传</h3><h6>表单提交上传通过IFormFile参数获取上传⽂件信息</h6><h6>AJAX请求上传,通过Request.Form.Files获取上传⽂件信息</h6><form method="post" enctype="multipart/form-data" action="/batch_upload_avatar"> <div class="form-group"><div class="col-md-10"><p>Upload one or more files using this form:</p><input type="file" id="files" name="files" multiple /></div></div><div class="form-group"><div class="col-md-10"><input type="submit" value="服务器⽅式上传" /></div></div></form></body></html>*Vue el-upload ⽅式<template><el-uploadclass="avatar-uploader"action="http://localhost:60548/api/v1.0/users/upload_avatar":headers="token":data="{ user_code: 666 }":show-file-list="false":on-success="handleAvatarSuccess":before-upload="beforeAvatarUpload"><img v-if="imageUrl" :src="imageUrl" class="avatar" /><i v-else class="el-icon-plus avatar-uploader-icon"></i></el-upload></template><script>import { getToken } from "@/utils/auth";export default {data() {return {token: { Authorization: `Bearer ${getToken()}` }};},};</script><style>.avatar-uploader .el-upload {border: 1px dashed #d9d9d9;border-radius: 6px;cursor: pointer;position: relative;overflow: hidden;}.avatar-uploader .el-upload:hover {border-color: #409eff;}.avatar-uploader-icon {font-size: 28px;color: #8c939d;width: 178px;height: 178px;line-height: 178px;text-align: center;}.avatar {width: 178px;height: 178px;display: block;}</style><script>export default {data() {return {imageUrl: "",};},methods: {handleAvatarSuccess(res, file) {this.imageUrl = URL.createObjectURL(file.raw); },beforeAvatarUpload(file) {const isLt2M = file.size / 1024 / 1024 < 2; return isLt2M;},},};</script>。
asp.netfileupload控件上传图片并预览图片
![asp.netfileupload控件上传图片并预览图片](https://img.taocdn.com/s3/m/b2c62357b207e87101f69e3143323968011cf4ab.png)
fileupload控件上传图⽚并预览图⽚本⽂为⼤家分享了fileupload控件实现上传图⽚后并进⾏预览图⽚的功能,并对web.config进⾏了配置,先看⼀下最终效果:页⾯代码:<form id="form1" runat="server"><div><asp:FileUpload ID="FileUpload1" runat="server" /><asp:Button ID="Button1" runat="server" Text="上传" Width="54px" OnClick="Button1_Click" /><asp:Label ID="Label1" runat="server" Text="" Style="color: Red"></asp:Label><asp:Image runat="server" ID="Image1" Style="z-index: 102; left: 20px; position: absolute;top: 49px" Width="73px" /></div></form>后台代码:using System;using System.Data;using System.Configuration;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;namespace Web.File{public partial class WebForm1 : System.Web.UI.Page{protected void Page_Load(object sender, EventArgs e){}#region ⽂件上传/// <summary>/// ⽂件上传/// </summary>protected void Button1_Click(object sender, EventArgs e){if (FileUpload1.FileName == ""){bel1.Text = "上传⽂件不能为空";return;}bool fileIsValid = false;//如果确认了上传⽂件,则判断⽂件类型是否符合要求if (this.FileUpload1.HasFile){//获取上传⽂件的后缀String fileExtension = System.IO.Path.GetExtension(this.FileUpload1.FileName).ToLower();String[] restrictExtension = { ".gif", ".jpg", ".bmp", ".png" };//判断⽂件类型是否符合要求for (int i = 0; i < restrictExtension.Length; i++){if (fileExtension == restrictExtension[i]){fileIsValid = true;}//如果⽂件类型符合要求,调⽤SaveAs⽅法实现上传,并显⽰相关信息if (fileIsValid == true){//上传⽂件是否⼤于10Mif (FileUpload1.PostedFile.ContentLength > (10 * 1024 * 1024)){bel1.Text = "上传⽂件过⼤";return;}try{this.Image1.ImageUrl = "~/File/" + FileUpload1.FileName;this.FileUpload1.SaveAs(Server.MapPath("~/File/") + FileUpload1.FileName);bel1.Text = "⽂件上传成功!";}catch{bel1.Text = "⽂件上传失败!";}finally{}}else{bel1.Text = "只能够上传后缀为.gif,.jpg,.bmp,.png的⽂件";}}}}#endregion}}Web.config 配置:<!--因为FileUpload 控件上传最⼤为4M,如果要上传更⼤⽂件,改下maxRequestLength的⼤⼩--><configuration><system.web><compilation debug="true" targetFramework="4.0" /><httpRuntime requestValidationMode="2.0" maxRequestLength="10485760" executionTimeout="3600" appRequestQueueLimit="10000"/></system.web></configuration>为⼤家附3个精彩的专题:亲,你可以在⾃⼰的项⽬中实现fileupload控件上传图⽚并进⾏预览图⽚的功能,这样⽹站更具有实⽤性,基本步骤就是这些,可能还有⼩编遗漏的地⽅,希望⼤家谅解。
ASP.NET实现文件图片上传下载处理
![ASP.NET实现文件图片上传下载处理](https://img.taocdn.com/s3/m/23219e77178884868762caaedd3383c4bb4cb416.png)
实现⽂件图⽚上传下载处理1.最简单的单⽂件上传(没花头)2.多⽂件上传3.客户端检查上传⽂件类型(以上传图⽚为例)4.服务器端检查上传⽂件类型(以上传图⽚为例)5.服务器端检查上传⽂件类型(可以检测真正⽂件名)6.上传⽂件⽂件名唯⼀性处理(时间戳+SessionID)7.上传图⽚⽣成等⽐例缩略图8.上传图⽚加⽔印(⽂字⽔印,图⽚⽔印,⽂字+图⽚⽔印)9.1.最简单的单⽂件上传(没花头)效果图:说明:这是最基本的⽂件上传,在1.x中没有这个FileUpload控件,只有html的上传控件,那时候要把html控件转化为服务器控件,很不好⽤。
其实所有⽂件上传的美丽效果都是从这个FileUpload控件衍⽣,第⼀个例⼦虽然简单却是根本。
后台代码:using System;using System.Data;using System.Configuration;using System.Collections;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;public partial class _Default : System.Web.UI.Page{protected void Page_Load(object sender, EventArgs e){}protected void bt_upload_Click(object sender, EventArgs e){try{if (FileUpload1.PostedFile.FileName == ""){this.lb_info.Text = "请选择⽂件!";}else{string filepath = FileUpload1.PostedFile.FileName;string filename = filepath.Substring(stIndexOf("\\") + 1);string serverpath = Server.MapPath("images/") + filename;FileUpload1.PostedFile.SaveAs(serverpath);this.lb_info.Text = "上传成功!";}}catch (Exception ex){this.lb_info.Text = "上传发⽣错误!原因是:" + ex.ToString();}}}前台代码:<table style="width: 343px"><tr><td style="width: 100px">单⽂件上传</td><td style="width: 100px"></td></tr><tr><td style="width: 100px"><asp:FileUpload ID="FileUpload1" runat="server" Width="475px" /></td><td style="width: 100px"><asp:Button ID="bt_upload" runat="server" OnClick="bt_upload_Click" Text="上传" /></td></tr><tr><td style="width: 100px; height: 21px;"><asp:Label ID="lb_info" runat="server" ForeColor="Red" Width="183px"></asp:Label></td></td></tr></table>2.多⽂件上传效果图:后台代码:using System;using System.Data;using System.Configuration;using System.Collections;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;public partial class _Default : System.Web.UI.Page{protected void Page_Load(object sender, EventArgs e){}protected void bt_upload_Click(object sender, EventArgs e){if ((FileUpload1.PostedFile.FileName == "" && FileUpload2.PostedFile.FileName == "")&&FileUpload3.PostedFile.FileName == "") {this.lb_info.Text = "请选择⽂件!";}else{HttpFileCollection myfiles = Request.Files;for (int i = 0; i < myfiles.Count; i++){HttpPostedFile mypost = myfiles[i];try{if (mypost.ContentLength > 0){string filepath = mypost.FileName;string filename = filepath.Substring(stIndexOf("\\") + 1);string serverpath = Server.MapPath("images/") + filename;mypost.SaveAs(serverpath);this.lb_info.Text = "上传成功!";}}catch (Exception error){this.lb_info.Text = "上传发⽣错误!原因:" + error.ToString();}}}}}前台代码:<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ""><html xmlns="" ><head runat="server"><title>多⽂件上传清清⽉⼉/21aspnet/</title></head><body><form id="form1" runat="server"><div><table style="width: 343px"><tr><td style="width: 100px">多⽂件上传</td><td style="width: 100px"></tr><tr><td style="width: 100px"><asp:FileUpload ID="FileUpload1" runat="server" Width="475px" /></td><td style="width: 100px"></td></tr><tr><td style="width: 100px"><asp:FileUpload ID="FileUpload2" runat="server" Width="475px" /></td><td style="width: 100px"></td></tr><tr><td style="width: 100px"><asp:FileUpload ID="FileUpload3" runat="server" Width="475px" /></td><td style="width: 100px"></td></tr><tr><td style="width: 100px"><asp:Button ID="bt_upload" runat="server" OnClick="bt_upload_Click" Text="⼀起上传" /> <asp:Label ID="lb_info" runat="server" ForeColor="Red" Width="183px"></asp:Label></td> <td style="width: 100px"></td></tr></table></div></form></body></html>3.客户端检查上传⽂件类型(以上传图⽚为例)效果图:后台代码和1.最简单的单⽂件上传⼀样;前台代码:<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ""><html xmlns="" ><head runat="server"><title>清清⽉⼉ ><script language="javascript">function Check_FileType(){var str=document.getElementById("FileUpload1").value;var pos = stIndexOf(".");var lastname = str.substring(pos,str.length)if (lastname.toLowerCase()!=".jpg" && lastname.toLowerCase()!=".gif"){alert("您上传的⽂件类型为"+lastname+",图⽚必须为.jpg,.gif类型");return false;}else{return true;}}</script></head><body><form id="form1" runat="server"><div><table style="width: 343px"><tr><td style="width: 104px">⽂件上传判断</td><td style="width: 100px"></td><td style="width: 104px"><asp:FileUpload ID="FileUpload1" runat="server" Width="400px" /></td><td style="width: 100px"><asp:Button ID="bt_upload" runat="server" OnClick="bt_upload_Click" Text="上传" OnClientClick="return Check_FileType()"/></td> </tr><tr><td style="width: 104px; height: 21px;"><asp:Label ID="lb_info" runat="server" ForeColor="Red" Width="183px"></asp:Label></td><td style="width: 100px; height: 21px"></td></tr></table></div></form></body></html>说明:点击上传时先触发客户端事件Check_FileType;4.服务器端检查上传⽂件类型(以上传图⽚为例)效果图:后台代码:using System;using System.Data;using System.Configuration;using System.Collections;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;public partial class _Default : System.Web.UI.Page{protected void Page_Load(object sender, EventArgs e){}protected void bt_upload_Click(object sender, EventArgs e){try{if (FileUpload1.PostedFile.FileName == ""){this.lb_info.Text = "请选择⽂件!";}else{string filepath = FileUpload1.PostedFile.FileName;if (IsAllowedExtension(FileUpload1) == true){string filename = filepath.Substring(stIndexOf("\\") + 1);string serverpath = Server.MapPath("images/") + filename;FileUpload1.PostedFile.SaveAs(serverpath);this.lb_info.Text = "上传成功!";}else{this.lb_info.Text = "请上传图⽚";}}}catch (Exception error){this.lb_info.Text = "上传发⽣错误!原因:" + error.ToString();}}public static bool IsAllowedExtension(FileUpload hifile){string strOldFilePath = "", strExtension = "";string[] arrExtension = { ".gif", ".jpg", ".jpeg", ".bmp", ".png" };if (hifile.PostedFile.FileName != string.Empty){strOldFilePath = hifile.PostedFile.FileName;strExtension = strOldFilePath.Substring(stIndexOf("."));for (int i = 0; i < arrExtension.Length; i++){return true;}}}return false;}}5.服务器端检查上传⽂件类型(可以检测真正⽂件名)其实⽅法4并不好,因为⽤户可以把XXX.txt伪装为XXX.jpg。
asp图片无组件上传与显示(测试过OK,提醒记得新建uploading文件夹否则提示错误)
![asp图片无组件上传与显示(测试过OK,提醒记得新建uploading文件夹否则提示错误)](https://img.taocdn.com/s3/m/cb86141acc7931b764ce150f.png)
asp图片无组件上传与显示(测试过OK,提醒记得新建uploading 文件夹否则提示错误)三个文件(index.asp upload.asp upfile.asp)一个文件夹存放上传图片的文件夹(uploading)一个无组件上传需要的upload_5xsoft.inc1.upload_5xsoft.inc<%dim upfile_5xSoft_StreamClass upload_5xSoftdim Form,File,VersionPrivate Sub Class_Initializedim iStart,iFileNameStart,iFileNameEnd,iEnd,vbEnter,iFormStart,iFormEnd,theFiledim strDiv,mFormName,mFormValue,mFileName,mFileSize,mFilePath,iDivLen,mStr Version="任翔专用上传程序"if Request.TotalBytes<1 then Exit Subset Form=CreateObject("Scripting.Dictionary")set File=CreateObject("Scripting.Dictionary")set upfile_5xSoft_Stream=CreateObject("Adodb.Stream")upfile_5xSoft_Stream.mode=3upfile_5xSoft_Stream.type=1upfile_5xSoft_Stream.openupfile_5xSoft_Stream.write Request.BinaryRead(Request.TotalBytes)vbEnter=Chr(13)&Chr(10)iDivLen=inString(1,vbEnter)+1strDiv=subString(1,iDivLen)iFormStart=iDivLeniFormEnd=inString(iformStart,strDiv)-1while iFormStart < iFormEndiStart=inString(iFormStart,"name=""")iEnd=inString(iStart+6,"""")mFormName=subString(iStart+6,iEnd-iStart-6)iFileNameStart=inString(iEnd+1,"filename=""")if iFileNameStart>0 and iFileNameStart<iFormEnd theniFileNameEnd=inString(iFileNameStart+10,"""")mFileName=subString(iFileNameStart+10,iFileNameEnd-iFileNameStart-10)iStart=inString(iFileNameEnd+1,vbEnter&vbEnter)iEnd=inString(iStart+4,vbEnter&strDiv)if iEnd>iStart thenmFileSize=iEnd-iStart-4elsemFileSize=0end ifset theFile=new FileInfotheFile.FileName=getFileName(mFileName)theFile.FilePath=getFilePath(mFileName)theFile.FileSize=mFileSizetheFile.FileStart=iStart+4theFile.FormName=FormNamefile.add mFormName,theFileelseiStart=inString(iEnd+1,vbEnter&vbEnter)iEnd=inString(iStart+4,vbEnter&strDiv)if iEnd>iStart thenmFormValue=subString(iStart+4,iEnd-iStart-4)elsemFormValue=""end ifform.Add mFormName,mFormValueend ifiFormStart=iformEnd+iDivLeniFormEnd=inString(iformStart,strDiv)-1wendEnd SubPrivate Function subString(theStart,theLen)dim i,c,stempupfile_5xSoft_Stream.Position=theStart-1stemp=""for i=1 to theLenif upfile_5xSoft_Stream.EOS then Exit forc=ascB(upfile_5xSoft_Stream.Read(1))If c > 127 Thenif upfile_5xSoft_Stream.EOS then Exit forstemp=stemp&Chr(AscW(ChrB(AscB(upfile_5xSoft_Stream.Read(1)))&ChrB(c))) i=i+1elsestemp=stemp&Chr(c)End IfNextsubString=stempEnd functionPrivate Function inString(theStart,varStr)dim i,j,bt,theLen,strInString=0Str=toByte(varStr)theLen=LenB(Str)for i=theStart to upfile_5xSoft_Stream.Size-theLenif i>upfile_5xSoft_Stream.size then exit Functionupfile_5xSoft_Stream.Position=i-1if AscB(upfile_5xSoft_Stream.Read(1))=AscB(midB(Str,1)) then InString=ifor j=2 to theLenif upfile_5xSoft_Stream.EOS theninString=0Exit forend ifif AscB(upfile_5xSoft_Stream.Read(1))<>AscB(MidB(Str,j,1)) then InString=0Exit Forend ifnextif InString<>0 then Exit Functionend ifnextEnd FunctionPrivate Sub Class_Terminateform.RemoveAllfile.RemoveAllset form=nothingset file=nothingupfile_5xSoft_Stream.closeset upfile_5xSoft_Stream=nothingEnd SubPrivate function GetFilePath(FullPath)If FullPath <> "" ThenGetFilePath = left(FullPath,InStrRev(FullPath, "\"))ElseGetFilePath = ""End IfEnd functionPrivate function GetFileName(FullPath)If FullPath <> "" ThenGetFileName = mid(FullPath,InStrRev(FullPath, "\")+1)ElseGetFileName = ""End IfEnd functionPrivate function toByte(Str)dim i,iCode,c,iLow,iHightoByte=""For i=1 To Len(Str)c=mid(Str,i,1)iCode =Asc(c)If iCode<0 Then iCode = iCode + 65535If iCode>255 TheniLow = Left(Hex(Asc(c)),2)iHigh =Right(Hex(Asc(c)),2)toByte = toByte & chrB("&H"&iLow) & chrB("&H"&iHigh)ElsetoByte = toByte & chrB(AscB(c))End IfNextEnd functionEnd ClassClass FileInfodim FormName,FileName,FilePath,FileSize,FileStartPrivate Sub Class_InitializeFileName = ""FilePath = ""FileSize = 0FileStart= 0FormName = ""End SubPublic function SaveAs(FullPath)dim dr,ErrorChar,iSaveAs=1if trim(fullpath)="" or FileSize=0 or FileStart=0 or FileName="" then exit function if FileStart=0 or right(fullpath,1)="/" then exit functionset dr=CreateObject("Adodb.Stream")dr.Mode=3dr.Type=1dr.Openupfile_5xSoft_Stream.position=FileStart-1upfile_5xSoft_Stream.copyto dr,FileSizedr.SaveToFile FullPath,2dr.Closeset dr=nothingSaveAs=0end functionEnd Class%>2.index.asp<form name="Form1" method="POST" action="add.asp"><textarea cols="100" name="image" rows="18" width="100%"></textarea></form><iframe border="0" frameBorder="0" noResize scrolling="no" width="100%"src="upload.asp"></iframe>(Textarea 显示图片, iframe显示上传页面upload.asp)3.upload.asp<form name="form" method="post" action="upfile.asp" enctype="multipart/form-data"> <p><input type="hidden" name="filepath" value="uploading"><input type="hidden" name="act" value="upload"><input type="file" name="file1" size=20><input type="submit" class=button name="Submit" value="上传图片"onclick="parent.document.forms[0].Submit.disabled=true"></p><p>类型:gif,jpg,png限制:100K</p></form>( enctype="multipart/form-data"用于表单里有图片上传)4.upfile.asp<!--#include file="upload_5xsoft.inc" --><html><head><title>文件上传</title></head><script>parent.document.forms[0].Submit.disabled=false;</script><%dim upload,file,formName,formPath,iCount,filename,fileExtset upload=new upload_5xSoft ''建立上传对象formPath=upload.form("filepath")''在目录后加(/)if right(formPath,1)<>"/" then formPath=formPath&"/"response.write "<body>"iCount=0for each formName in upload.file ''列出所有上传了的文件set file=upload.file(formName) ''生成一个文件对象if file.filesize<100 thenresponse.write "请选择你要上传的文件[ <a href=# onclick=history.go(-1)>重新上传</a> ]"response.endif file.filesize>100*1000 thenresponse.write "文件大小超过了限制100K[ <a href=# onclick=history.go(-1)>重新上传</a> ]"response.endend iffileExt=lcase(right(file.filename,4))uploadsuc=falseForum_upload="gif,jpg,png"Forumupload=split(Forum_upload,",")for i=0 to ubound(Forumupload)if fileEXT="."&trim(Forumupload(i)) thenuploadsuc=trueexit forelseuploadsuc=falseend ifnextif uploadsuc=false thenresponse.write "文件格式不正确[ <a href=# onclick=history.go(-1)>重新上传</a> ]"response.endend ifrandomizeranNum=int(90000*rnd)+10000filename=formPath&year(now)&month(now)&day(now)&hour(now)&minute(now)&secon d(now)&ranNum&fileExtif file.FileSize>0 then ''如果FileSize > 0 说明有文件数据file.SaveAs Server.mappath(FileName) ''保存文件for i=0 to ubound(Forumupload)if fileEXT="."&trim(Forumupload(i)) thenresponse.write "<font color=#FF0000>文件上传成功</font>[ <a href=# onclick=history.go(-1)>继续上传</a>]"exit forend ifstrJS="<SCRIPT language=javascript>" & vbcrlfstrJS=strJS & "var oImg=parent.document.createElement('IMG');"& vbcrlfstrJS=strJS & "oImg.src='" &FileName& "';"& vbcrlfstrJS=strJS & "parent.Form1.image.appendChild(oImg);"& vbcrlfstrJS=strJS & "</script>"response.write strJSnextiCount=iCount+1set file=nothingnextset upload=nothing ''删除此对象response.end%>。
ASP.NET上传图片的方法探讨(C#)
![ASP.NET上传图片的方法探讨(C#)](https://img.taocdn.com/s3/m/c87d45e69e31433239689319.png)
图片 是不 科 学 的 , 那 么 在 应用 程序 中 自动缩 放 图片是 必 须 的 。 使 用S y s t e m. D r a wi n g 类 可以 很好解 决这 个 问题 , 其 中B i t ma p是用 于处 理 由像素 数据 定义 的 图像 的 对 象 , 可 以用 来 自动 缩放 图片 的尺 寸。 首先 引 用命 名 空 间S y s t e m. D r a wi n g , 具 体 方法 如 下 :
s t r i n g il f e na m e : Sy s t e m. Da t e Ti me. NO W. To Ff l e Ti me ( ) . To S t r i n g ( ) ;
( c o mp l e t e i f l e n a me ) ) ; / / 打开 源 图片
I m age i m gO Ut S =Bi t m a P. From Fi l e( Se r ve r. M aPPa t h
在代 码视 图中 为B u t t o n 控 件 的C i r c k 事件 添 加如 下代 码 : F i l e Up L o a d 1 . P o s t e d F i l e . S a v e As ( S e r v e r . Ma p P a t h ( ” t e mp. J P g ’ ) ) ; 其 中S e r v e r . Ma p P a t h 返 回与 We b 服务 器上 的指 定虚 拟路径 相对 应 的物理 文 件路 径 , 在 源 视 图 中将 B u t t o n 的o n di c k 的属性 设置 为 ” 上 传B u t t o n — C H c k ” , 就 实现 了图片 的上 传 。 1. 图 片 的文 件 名 尽 管 图片上 传 的基本 方法 十分 简单 , 但 问题 也是存 在明显 的 , 就 是上 传的 图片文 件 名都 为t e mp. J P g , 不 管什 么类 型 图片 , 都存 储 为 . J P g 格式, 不 管上 传 多少 个 图片 , 都 只保存 最后 一次上 传 , 不管有 多少用 户上传 图片 , 还是 只保 留最 后一 个 用户 的 图片 , 因此上 传 图片 的文件 名必 须遵 循 一套 规则 。 上 传 图片 文件名 规则 , 一 般 采用时 间字 符 串, D a t e T i me . N o w. T o F l f e T i me 0可 以获得 当前 时 间的长 整型 数字 , 这个 数字 应该 是 由年精 确到 微秒 的 , 所 以 用它作 文件 名 的话几 乎不 会重 复 , 如果是 多 用户 同时操 作的程 序( 比如 网站 ) 可 以考虑 加上 用户 的 或编 号、 用 户名做 尾 缀, 或 者增加 一个多 为 的随机数 , 或 者 以文件 的 字节 数作 为 尾缀 , 都 是 比较可 靠 的做法 。 s t r i n g f i l e n a me: S y s t e m. D a t e T i me . No w. T o F i r e Ti me ( ) . T o S t r i n g ( ) ; 2. 图 片 的 类型 利用 F i l e U p L o a d 的G e t E x t e n s i o n 方法 直接 获 取 图片 类型 名 。 s t r i n g i f l e E x t e n s i o n =S y s t e m. I O. P a t h . G e t E x t e n s i o n ( F i 】 e Up L o a d 1 . F l f e Na me ) . T o L o we r ( ) ; 结 合 图片 的文 件名 命名 规 则和 类型 获取 的方 法 , B u t t o n 控件 的C l i c k  ̄ 件 代码 应为 :
ASP.NET上传图片至数据库并显示图片...
![ASP.NET上传图片至数据库并显示图片...](https://img.taocdn.com/s3/m/aa8b07e0710abb68a98271fe910ef12d2af9a9f7.png)
上传图片至数据库并显示图片...今天,和大家讨论一下在中,如何上传图片至数据库,然后再将图片读取显示的问题。
欢迎高手提出自己的方法目前,我主要用到以下两种方法:1:上传图片的相对路径到数据库中相应字段里,读取显示时,将控件(假设用的是Image控件)的ImageUrl属性指向该相对路径即可。
2:将图片以二进制流的方式整体上传到数据库里,读取显示时,以二进制流的方式整体读出。
这种方法稍微麻烦一点,但保存的是图片整体到数据库里。
第一种方法,实现起来比较简单,因为存入数据库里的只是图片相对路径,当然,同时也就有很大的局限性,由于是相对路径,所以当本地的图片变换了位置或移除,或是在其他主机上浏览该图片时,就无法显示了。
第二种方法,就比较灵活了,可以用在交互性的页面,比如校友录,因为上传的是整张图片,所以只要读取正确,就能任何主机上显示出来。
下面,分别通过实际的代码,介绍这两种方法。
在这两个方法里,我将用到一个控件:FileUpload,该控件的具体用法参见百度谷歌。
学习过程中,最好的老师就是他们俩。
1:上传图片上传图片相对路径,并读取显示。
数据库里的字段很简单,就两个Image_ID int identity(1,1) primarykey not nullImage_Wpath varchar(50) nullImage_Wpath 用来保存图片的相对路径很简单的界面(其实是有点丑。
):点击查看大图这里注意,我需要上传的文件都放在文件夹“Image”,在后面的上传路径里就需要这个文件夹。
下面是效果图:点击查看大图我在输入框里填入Image_ID的值,读取指定的图片,在图片的下面,显示出该图片的相对路径。
接下来,我们看一下具体代码实现上传和读取显示功能。
在项目里,有一个sqlHelper类,是一些常用的数据访问方法。
这里就不详细讲了。
上传按钮里的事件:CODE:1.protected void Button1_Click(object sender, EventArgs e)2.3.{4.5.string name = FileUpload1.FileName;//获取文件名6.7.string type = name.Substring(stIndexOf(".") + 1);8.9.//获取文件类型10.11.string ipath = Server.MapPath("Image") + "\\" + n ame;12.13.//获取文件路径14.15.string wpath = "Image\\" + name;16.17.//[color=red]设置文件保存相对路径18.19.(这里的路径起始就是我们存放图片的文件夹名)[/color]20.21.22.23.string query1 = "insert into Images values24.25.('" + wpath + "')";26.27.28.29.if (type == "jpg" || type == "gif" ||30.31.type == "bmp" || type == "png")32.33.{34.35.FileUpload1.SaveAs(ipath); //服务器保存路径36.37.sqlHelper.ExecterNonQuery(query1);38.39.}40.41.}42.显示按钮事件:CODE:1.protected void Button2_Click(object sender, EventArgs e)2.3.{4.5.string query2 = "select * from Images where6.7.Image_ID=" + Convert.ToInt32(TextBox1.Text);8.9.SqlDataReader sdr = sqlHelper.GetReader(query2);10.11.string wpath2 = "";12.13.while (sdr.Read())14.15.{16.17.wpath2 = sdr[1].T oString();18.19.//获得相对路径20.21.}22.23.sdr.Close();24.25.Image1.ImageUrl = wpath2;26.27.//图片显示路径就是相对路径28.bel1.Text = wpath2; //显示相对路径30.31.}32.2:以二进制流的方式存入数据库,并读取显示图片。
jsp页面上传图片文件无刷新
![jsp页面上传图片文件无刷新](https://img.taocdn.com/s3/m/f4578d750b1c59eef8c7b494.png)
最近做SSH项目碰到一个问题,我在页面上想上传一个图片文件到服务器,但是在上传前希望能在页面上看到图片的预览。
查了一下资料,发现有几种方式可以完成这个功能。
一种是通过javascript来实现这个预览的功能,但是这种方法对浏览器有限制,有的浏览器用此方法无效。
一种是通过ajax实现,还有一种就是通过无刷新页面上传文件到服务器,通过显示服务器上的临时图片文件也可以实现预览的效果。
下面讲的就是最后一种方式。
先看页面文件test.html源码:<!DOCTYPE html><html><head><title>test.html</title><meta name="keywords"content="keyword1,keyword2,keyword3"><meta name="description"content="this is my page"> <meta name="content-type"content="text/html; charset=GB18030"><!--<link rel="stylesheet" type="text/css"href="./styles.css">--></head><body><form action="/ECSystem/imgupload"id="form1" name="form1"encType="multipart/form-data"method="post"target="hidden_frame"><input type="file"id="file"name="file"style="width:450" accept=".jpg, .gif"><INPUT type="submit"value="上传文件"><spanid="msg"></span><br><font color="red">支持JPG,JPEG,GIF,BMP,SWF,RMVB,RM,AVI文件的上传</font><iframe name='hidden_frame'id="hidden_frame"style='display:none'></iframe></form></body></html>上面的源码中,要上传图片文件form的属性里必须有encType="multipart/form-data"method="post"z,想要页面不刷新,“target="hidden_frame"”这个是必要的设置,表示页面的action请求刷新到iframe里,不必刷新整个页面。
基于ASP.NET2.0和流模式的图片上传与显示
![基于ASP.NET2.0和流模式的图片上传与显示](https://img.taocdn.com/s3/m/a46647f1aef8941ea76e056d.png)
收稿 日期 : 0 1O — 3 2 1 一 4 2
基金 项 目 : 夷 学 院 青 年 教 师 专 项 科 研 基 金 资 助项 目(q 0 0 5 武 x 212) 作者 简 介 : 连雁 平 (9 1) 男 , 建 武 夷 山 人 , 夷 学 院 讲 师 。 18 一 , 福 武
第 2 卷第 6 9 期
21 0 1年 1 1月
佛 山科 学技 术学 院学报 ( 自然科 学版 )
J un l f oh nUnvri N t rl c n eE io ) o r a o s a ies y( au a S i c dt n F t e i
Vo . 9 No 6 12 .
件名或 路径保存 在 指定 的数据库 表 的字 段 里 ; 二是 将 图片转换 成二进 制 的数 据格 式 , 通过 流模 式处理 方 法 将转 换后 的二进 制数据 保存 在指定 的数 据库 表的字 段里【 。 1 方式存 储方 便 , 1第 种 ] 对数 据库 系统来 说 负担较 小 , 但是 由于它是 将 图片文件 名或路 径 当作 普通 字符 串直接存 储在数 据库 表 的字 段里 , 以安 全 所 性较 差 , 易被修 改 、 除 ; 2种方 式是将 图片内容转 换成 二进制数 据保存 , 容 删 第 不易被修 改 、 删除 , 全性 安 较高 。 ] 本文 主要 阐述 在 AS . T2 0开 发平 台下 , P NE . 如何实 现 电子 商务平 台图 片路径 保存技术 , 以及 基
内容 之 一 。 阐述 在 A P NE 2 0开 发 平 台 下 , 何 实 现 电子 商 务 平 台 图 片路 径 保 存 技 术 , 及基 于流 模 式 的二 S. T. 如 以 进 制 图 片上 传 与 显 示 处 理 。 关键词 ; 电子 商 务 AS . T2 0流 模 式 ; 传 与 显 示 P NE . ; 上 中图 分 类 号 : 3 14 TP 9 . 1 文献标志码 : A
asp.net图片上传实例
![asp.net图片上传实例](https://img.taocdn.com/s3/m/ccc10d4c302b3169a45177232f60ddccda38e67b.png)
图⽚上传实例第⼀、图⽚上传,代码如下:xxx.aspx复制代码代码如下:<td class="style1"><asp:FileUpload ID="FileUpload1" runat="server" /><asp:Button ID="Button1" runat="server" Text="上传⼀般图⽚" onclick="Button1_Click" /></td><td class="style3"><asp:Image ID="Image1" runat="server" Height="200px" Width="200px" /></td>xxx.aspx.cs复制代码代码如下:protected void Button1_Click(object sender, EventArgs e){for (int i = 0; i < Request.Files.Count; i++){HttpPostedFile file = Request.Files[i];if (file.ContentLength > 0){if (file.ContentType.Contains("image/")){using (System.Drawing.Image img = System.Drawing.Image.FromStream(file.InputStream)){string FileName = System.IO.Path.GetFileName(file.FileName);string[] SplitFileName = FileName.Split('.');string AtterFileName = DateTime.Now.ToString("yyyMMddHHmmss")+"." + SplitFileName[1]; img.Save(Server.MapPath("/upload/" + AtterFileName));this.Image1.ImageUrl = "upload/" + AtterFileName;}}else{Response.Write("<script>alert('该⽂件不是图⽚格式!');</script>");}}else{Response.Write("<script>alert('请选择要上传的图⽚');</script>");}}}第⼆、添加⽂字⽔印的图⽚上传,代码如下:xxx.aspx复制代码代码如下:<td class="style1"><asp:FileUpload ID="FileUpload2" runat="server" /><asp:Button ID="Button2" runat="server" Text="上传⽂字图⽚" onclick="Button2_Click" /></td><td><asp:Image ID="Image2" runat="server" Height="200px" Width="200px" /></td>xxx.aspx.cs复制代码代码如下:protected void Button2_Click(object sender, EventArgs e){for (int i = 0; i < Request.Files.Count; i++){HttpPostedFile file = Request.Files[i];if (file.ContentLength > 0){if (file.ContentType.Contains("image/")){using (System.Drawing.Image img = System.Drawing.Image.FromStream(file.InputStream)){using (Graphics g = Graphics.FromImage(img)){g.DrawString("我的图⽚", new Font("宋体", 14), Brushes.Red, 0, 0);}string FileName = System.IO.Path.GetFileName(file.FileName);string[] SplitFileName = FileName.Split('.');string AtterFileName = DateTime.Now.ToString("yyyMMddHHmmss") + "." + SplitFileName[1]; img.Save(Server.MapPath("/upload/" + AtterFileName));this.Image2.ImageUrl = "upload/" + AtterFileName;}}else{Response.Write("<script>alert('该⽂件不是图⽚格式!');</script>");}}else{Response.Write("<script>alert('请选择要上传的图⽚');</script>");}}}第三、添加图⽚⽔印的图⽚上传,代码如下:xxx.aspx复制代码代码如下:<td class="style1"><asp:FileUpload ID="FileUpload3" runat="server" /><asp:Button ID="Button3" runat="server" Text="上传⽔印图⽚" onclick="Button3_Click" /></td><td><asp:Image ID="Image3" runat="server" Height="200px" Width="200px" /></td>xxx.aspx.cs复制代码代码如下:protected void Button3_Click(object sender, EventArgs e){for (int i = 0; i < Request.Files.Count; i++){HttpPostedFile file = Request.Files[i];if (file.ContentLength > 0){if (file.ContentType.Contains("image/")){string fileName = file.FileName;using (System.Drawing.Image img = System.Drawing.Image.FromStream(file.InputStream)){using (System.Drawing.Image imgWater =System.Drawing.Image.FromFile(Server.MapPath("/img/czlogo.jpg"))){using (Graphics g = Graphics.FromImage(img)){g.DrawImage(imgWater, 0, 0);}string[] SplitFileName = fileName.Split('.');string AtterFileName = DateTime.Now.ToString("yyyMMddHHmmss") + "." + SplitFileName[1]; img.Save(Server.MapPath("/upload/" + AtterFileName));this.Image3.ImageUrl = "upload/" + AtterFileName;}}}else{Response.Write("<script>alert('该⽂件不是图⽚格式!');</script>");}}else{Response.Write("<script>alert('请选择要上传的图⽚');</script>");}}}第四、上传图⽚浓缩图,代码如下:xxx.aspx复制代码代码如下:<td class="style1"><asp:FileUpload ID="FileUpload4" runat="server" /><asp:Button ID="Button4" runat="server" Text="上传浓缩图⽚" onclick="Button4_Click" /></td><td><asp:Image ID="Image4" runat="server" Height="200px" Width="200px" /></td>xxx.aspx.cs复制代码代码如下:protected void Button4_Click(object sender, EventArgs e){for (int i = 0; i < Request.Files.Count; i++){HttpPostedFile file = Request.Files[i];if (file.ContentLength > 0){if (file.ContentType.Contains("image/")){using (System.Drawing.Image img = System.Drawing.Image.FromStream(file.InputStream)){using (System.Drawing.Image imgThumb = new Bitmap(200, 100)){using (Graphics g = Graphics.FromImage(imgThumb)){g.DrawImage(img, new Rectangle(0, 0, imgThumb.Width, imgThumb.Height), new Rectangle(0, 0, img.Width, img.Height), GraphicsUnit.Pixel);}string fileName = file.FileName;string[] SplitFileName = fileName.Split('.');string AtterFileName = DateTime.Now.ToString("yyyMMddHHmmss") + "." + SplitFileName[1];img.Save(Server.MapPath("/upload/" + AtterFileName));this.Image4.ImageUrl = "upload/" + AtterFileName;}}}else{Response.Write("<script>alert('该⽂件不是图⽚格式!');</script>");}}else{Response.Write("<script>alert('请选择要上传的图⽚');</script>");}}}。
ASP net图片上传预览及无刷新上传
![ASP net图片上传预览及无刷新上传](https://img.taocdn.com/s3/m/bb37f90deff9aef8941e060e.png)
图片上传预览及无刷新上传JS代码如下://清空File控件的值,并且预览处显示默认的图片function clearFileInput(){var form = document.createElement('form');document.body.appendChild(form);//记住file在旧表单中的的位置var file = document.getElementById("idFile");var pos = file.nextSibling;form.appendChild(file);form.reset();//通过reset来清空File控件的值document.getElementById("colspan").appendChild(file);document.body.removeChild(form);//在预览处显示图片这是在浏览器支持滤镜的情况使用的document.getElementById("idImg").style.filter ="progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='scale',src='images/abshiu.jpg'";//这是是火狐里面显示默认图片的if (erAgent.indexOf('Firefox') >= 0){$("#idImg").attr('src', 'images/abshiu.jpg');}}HTML代码如下:<table border="0" class="perview"><tr><th width="45%">选择文件</th><th width="45%">预览图</th><th width="10%">上传图片</th></tr><tr><td><span id="colspan"><input id="idFile" runat="server" name="pic" type="file"/></span> <input type="button" id="resets" name="resets" value="还原"onclick="clearFileInput()"/></td><td align="center"><img id="idImg" src="images/abshiu.jpg"/></td><td><input type="button" name="resets" value="上传保存图片" onclick="upLoadFile()"/></td></tr></table><script>var ip = new ImagePreview($$("idFile"), $$("idImg"), {maxWidth: 200, maxHeight: 200, action: "ImagePreview.ashx"});ip.img.src = ImagePreview.TRANSPARENT;ip.file.onchange = function() { ip.preview(); };</script>做到这里的话预览效果就已经搞定啦,然后就是无刷新上传,虽然cloudgamer的博客里面有简便无刷新文件上传系统,但是我没有采用,而是使用了jquery.form.js来做无刷新上传效果,代码如下:function upLoadFile()var options = {type: "POST",url: 'Files.ashx',success: showResponse};// 将options传给ajaxForm$('#myForm').ajaxSubmit(options);}function showResponse(){alert("上传成功!");}关于jquery.form.js的API,百度下吧。
ASP.NET图片上传实例(附源码)
![ASP.NET图片上传实例(附源码)](https://img.taocdn.com/s3/m/b957c5cd5122aaea998fcc22bcd126fff7055da9.png)
图⽚上传实例(附源码)由于需要图⽚上传的功能,所以花了⼀些时间⽹上找相关资料终于搞定,效果图如下:下⾯的是解决⽅案截图和上传的图⽚截图:下⾯是代码:1.界⾯代码<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="UploadPic.aspx.cs" Inherits="Pic_Try.UploadPic" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="/1999/xhtml"><head runat="server"><title>图⽚上传和显⽰</title><style type="text/css">.pic_text{ color:Red;}.pic_label { color:Gray; margin-top:5px; margin-bottom:5px;}.pic_image { margin:5px;}</style></head><body><form id="form1" runat="server"><div class="pic_image"><asp:Image ID="pic" runat="server" /></div><div><asp:FileUpload ID="pic_upload" runat="server" /><asp:Label ID="lbl_pic" runat="server" class="pic_text"></asp:Label></div> <div class="pic_label">上传图⽚格式为.jpg, .gif, .bmp,.png,图⽚⼤⼩不得超过8M</div><div><asp:Button ID="btn_upload" runat="server" Text="上传" onclick="btn_upload_Click"/></div></form></body></html>2.后台代码using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.IO;using System.Security.Cryptography;using System.Web.Security;namespace Pic_Try{public partial class UploadPic : System.Web.UI.Page{protected void Page_Load(object sender, EventArgs e){}protected void btn_upload_Click(object sender, EventArgs e){Boolean fileOk = false;if (pic_upload.HasFile)//验证是否包含⽂件{//取得⽂件的扩展名,并转换成⼩写string fileExtension = Path.GetExtension(pic_upload.FileName).ToLower();//验证上传⽂件是否图⽚格式fileOk = IsImage(fileExtension);if (fileOk){//对上传⽂件的⼤⼩进⾏检测,限定⽂件最⼤不超过8Mif (pic_upload.PostedFile.ContentLength < 8192000){string filepath = "/images/";if (Directory.Exists(Server.MapPath(filepath)) == false)//如果不存在就创建file⽂件夹{Directory.CreateDirectory(Server.MapPath(filepath));}string virpath = filepath + CreatePasswordHash(pic_upload.FileName, 4) + fileExtension;//这是存到服务器上的虚拟路径 string mappath = Server.MapPath(virpath);//转换成服务器上的物理路径pic_upload.PostedFile.SaveAs(mappath);//保存图⽚//显⽰图⽚pic.ImageUrl = virpath;//清空提⽰lbl_pic.Text = "";}else {pic.ImageUrl = "";lbl_pic.Text = "⽂件⼤⼩超出8M!请重新选择!";}}else {pic.ImageUrl = "";lbl_pic.Text = "要上传的⽂件类型不对!请重新选择!";}}else{pic.ImageUrl = "";lbl_pic.Text = "请选择要上传的图⽚!";}}/// <summary>/// 验证是否指定的图⽚格式/// </summary>/// <param name="str"></param>/// <returns></returns>public bool IsImage(string str) {bool isimage = false;string thestr = str.ToLower();//限定只能上传jpg和gif图⽚string[] allowExtension = { ".jpg", ".gif", ".bmp",".png" };//对上传的⽂件的类型进⾏⼀个个匹对for (int i = 0; i < allowExtension.Length; i++){if (thestr == allowExtension[i]){isimage = true;break;}}return isimage;}/// <summary>/// 创建⼀个指定长度的随机salt值/// </summary>public string CreateSalt(int saltLenght){//⽣成⼀个加密的随机数RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();byte[] buff = new byte[saltLenght];rng.GetBytes(buff);//返回⼀个Base64随机数的字符串return Convert.ToBase64String(buff);}/// <summary>/// 返回加密后的字符串/// </summary>public string CreatePasswordHash(string pwd, int saltLenght){string strSalt = CreateSalt(saltLenght);//把密码和Salt连起来string saltAndPwd = String.Concat(pwd, strSalt);//对密码进⾏哈希string hashenPwd = FormsAuthentication.HashPasswordForStoringInConfigFile(saltAndPwd, "sha1");//转为⼩写字符并截取前16个字符串hashenPwd = hashenPwd.ToLower().Substring(0, 16);//返回哈希后的值return hashenPwd;}}}3.最后防⽌上传⼤⽂件图⽚时报错,配置⽂件添加配置<?xml version="1.0" encoding="utf-8"?><!--如何配置 应⽤程序的详细消息--><configuration><system.web><compilation debug="true" targetFramework="4.0" /><httpRuntime executionTimeout="240" maxRequestLength="8192000"/> </system.web></configuration>的源码下载。
基于ASP.NET 2.0的数据库图片显示和上传方法
![基于ASP.NET 2.0的数据库图片显示和上传方法](https://img.taocdn.com/s3/m/6783f185b1717fd5360cba1aa8114431b90d8ef3.png)
基于 2.0的数据库图片显示和上传方法
孙思良;周少云
【期刊名称】《电脑开发与应用》
【年(卷),期】2008(021)007
【摘要】为了实现基于 2.0的SQL Server数据库的图片显示,在解决方案资源管理器中设计了两个文件:"CategoriesPicture.vb类"和"Handler.ashx一般处理程序",分别实现以下功能:从数据库中按形参读取图片数据;调用CategoriesPicture.vb类从数据库读取图片数据,并转换为可由Html标记显示的形式.
【总页数】3页(P40-42)
【作者】孙思良;周少云
【作者单位】大理学院,大理,671000;大理学院,大理,671000
【正文语种】中文
【中图分类】TP393.09
【相关文献】
中文件上传到数据库与上传到文件系统的比较 [J], 卢宇星
2.基于 2.0的金属材料性能数据库检索系统设计 [J], 沈军;朱亦钢
3.基于 2.0的文件上传研究 [J], 徐安凤;黄河涛
4.基于和Oracle数据库的图片上传和查看 [J], 颜波;孙宏波;杨融菲;肖田元
2.0中文件上传安全解决方案 [J], 李万彪
因版权原因,仅展示原文概要,查看原文内容请购买。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
图片上传预览及无刷新上传JS代码如下://清空File控件的值,并且预览处显示默认的图片function clearFileInput(){var form = document.createElement('form');document.body.appendChild(form);//记住file在旧表单中的的位置var file = document.getElementById("idFile");var pos = file.nextSibling;form.appendChild(file);form.reset();//通过reset来清空File控件的值document.getElementById("colspan").appendChild(file);document.body.removeChild(form);//在预览处显示图片这是在浏览器支持滤镜的情况使用的document.getElementById("idImg").style.filter ="progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='scale',src='images/abshiu.jpg'";//这是是火狐里面显示默认图片的if (erAgent.indexOf('Firefox') >= 0){$("#idImg").attr('src', 'images/abshiu.jpg');}}HTML代码如下:<table border="0" class="perview"><tr><th width="45%">选择文件</th><th width="45%">预览图</th><th width="10%">上传图片</th></tr><tr><td><span id="colspan"><input id="idFile" runat="server" name="pic" type="file"/></span> <input type="button" id="resets" name="resets" value="还原"onclick="clearFileInput()"/></td><td align="center"><img id="idImg" src="images/abshiu.jpg"/></td><td><input type="button" name="resets" value="上传保存图片" onclick="upLoadFile()"/></td></tr></table><script>var ip = new ImagePreview($$("idFile"), $$("idImg"), {maxWidth: 200, maxHeight: 200, action: "ImagePreview.ashx"});ip.img.src = ImagePreview.TRANSPARENT;ip.file.onchange = function() { ip.preview(); };</script>做到这里的话预览效果就已经搞定啦,然后就是无刷新上传,虽然cloudgamer的博客里面有简便无刷新文件上传系统,但是我没有采用,而是使用了jquery.form.js来做无刷新上传效果,代码如下:function upLoadFile()var options = {type: "POST",url: 'Files.ashx',success: showResponse};// 将options传给ajaxForm$('#myForm').ajaxSubmit(options);}function showResponse(){alert("上传成功!");}关于jquery.form.js的API,百度下吧。
#myForm就是页面的form的ID,Files.ashx则负责图片的上传处理,Files.ashx的代码如下:public class File_WebHandler : IHttpHandler{public void ProcessRequest(HttpContext context){HttpFileCollection files = context.Request.Files;if (files.Count > 0){Random rnd = new Random();for (int i = 0; i < files.Count; i++){HttpPostedFile file = files[i];if (file.ContentLength > 0){string fileName = file.FileName;string extension = Path.GetExtension(fileName);int num = rnd.Next(5000, 10000);string path = "file/" + num.ToString() + extension;file.SaveAs(System.Web.HttpContext.Current.Server.MapPath(path));}}}}public bool IsReusable{get{return false;}}代码到这里一个简单的例子也就完成啦。
附上小例子的源码:图片上传预览及无刷新上传使用JQuery上传插件Uploadify 3.1无刷新上传图片示例.aspx文件:<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="/1999/xhtml" ><head runat="server"><title>无标题页</title><style type="text/css">#preview{margin: 2px 0 0 0;}#previewImage{ border:1px solid #ddd; padding:3px;}</style><link rel="stylesheet" type="text/css"href="jQueryPlugin/Uploadify/uploadify.css" /><script src="js/jquery.min.js" type="text/javascript"></script><script type="text/javascript" src="js/DrawImage.js"></script><script src="jQueryPlugin/Uploadify/jquery.uploadify-3.1.min.js"type="text/javascript"></script><script type="text/javascript">$(function () {$("#uploadImage").uploadify({width: 100,height: 26,swf: 'jQueryPlugin/Uploadify/uploadify.swf', //[*]swf的路径uploader: 'HttpHandler/Uploadify.ashx', //[*]一般处理程序cancelImg: 'jQueryPlugin/Uploadify/uploadify-cancel.png', //取消图片路径multi: false,'fileTypeDesc': '图片文件',fileTypeExts: '*.gif;*.jpg;*.jpeg;*.png', //允许上传的文件类型,使用分号(”;)”分割例如:*.jpg;*.gif,默认为null(所有文件类型)'fileSizeLimit': '6000KB',onUploadSuccess: function (file, data, response) {//上传完成时触发(每个文件触发一次)if (data.indexOf('错误提示') > -1) {alert(data);}else {$("#previewImage").attr("src",data.substr(2)).hide().fadeIn(2000);}},'onUploadError': function (file, errorCode, errorMsg, errorString) {//当单个文件上传出错时触发alert('文件:' + + ' 上传失败: ' + errorString);},buttonText: '选择图片'});});</script></head><body><form id="form1" runat="server"><div id="upload"><input type="file" name="uploadImage" id="uploadImage" /></div><div id="preview"><img id="previewImage" src="images/no_pic.gif" alt="暂无图片" onload="DrawImage(this,120,120,'')" /></div></form></body></html>Uploadify.ashx文件代码:using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.IO;namespace CCMS.Web.HttpHandler{/// <summary>/// Uploadify 的摘要说明/// </summary>public class Uploadify : IHttpHandler{protected string AllowExt ="7z|aiff|asf|avi|bmp|csv|doc|docx|fla|flv|gif|gz|gzip|jpeg|jpg|mid|mo v|mp3|mp4|mpc|mpeg|mpg|ods|odt|pdf|png|ppt|pptx|pxd|qt|ram|rar|rm|rmi |rmvb|rtf|sdc|sitd|swf|sxc|sxw|tar|tgz|tif|tiff|txt|vsd|wav|wma|wmv|x ls|xlsx|xml|zip";//支持的文件格式int FileMaxSize = 10240;//文件大小,单位为Kpublic void ProcessRequest(HttpContext context){context.Response.ContentType = "text/plain";//context.Response.Write("Hello World");//HttpPostedFile file = context.Request.Files[0];//获取上传文件方式一HttpPostedFile fileUpload =context.Request.Files["Filedata"];//获取上传文件方式二if (fileUpload != null){try{string UploadDir = "~/upload/Uploadify/";//图片保存的文件夹//图片保存的文件夹路径string path = context.Server.MapPath(UploadDir);//每天上传的图片一个文件夹string folder = DateTime.Now.ToString("yyyyMM");//如果文件夹不存在,则创建if (!Directory.Exists(path + folder)){Directory.CreateDirectory(path + folder);}//上传图片的扩展名string fileExtension =fileUpload.FileName.Substring(stIndexOf('.'));//判断文件格式if (!CheckValidExt(fileExtension)){context.Response.Write("错误提示:文件格式不正确!" + fileExtension);return;}//判断文件大小if (fileUpload.ContentLength > FileMaxSize * 1024){context.Response.Write("错误提示:上传的文件(" + fileUpload.FileName + ")超过最大限制:" + FileMaxSize + "KB");return;}//保存图片的文件名//string saveName = Guid.NewGuid().ToString() + fileExtension;//使用时间+随机数重命名文件string strDateTime =DateTime.Now.ToString("yyMMddhhmmssfff");//取得时间字符串Random ran = new Random();string strRan = Convert.ToString(ran.Next(100, 999));//生成三位随机数string saveName = strDateTime + strRan + fileExtension;//保存图片fileUpload.SaveAs(path + folder + "/" + saveName);context.Response.Write(UploadDir + folder + "/" + saveName);}catch{context.Response.Write("错误提示:上传失败");}}}public bool IsReusable{get{return false;}}#region 检测扩展名的有效性 bool CheckValidExt(string sExt)/// <summary>/// 检测扩展名的有效性/// </summary>/// <param name="sExt">文件名扩展名</param>/// <returns>如果扩展名有效,返回true,否则返回false.</returns>public bool CheckValidExt(string strExt){bool flag = false;string[] arrExt = AllowExt.Split('|');foreach (string filetype in arrExt){if (filetype.ToLower() == strExt.ToLower().Replace(".", "")){flag = true;break;}}return flag;}#endregion} }。