aspx代码:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> </head> <body> <form id="form1" runat="server"> <div> <br /> <asp:FileUpload ID="FileUpload1" runat="server" /> <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="上传" /> <br /> <br /> <br /> <div id="localImag" style="width: 200px; height: 200px"> <img id="preview" alt="预览图片" src="images/qiye.png" width="200" height="200" /> <asp:FileUpload ID="PicLoad" Width="200px" Height="200px" style="position:relative; top:-200px; opacity:0" runat="server" onchange="javascript:setImagePreview(this,localImag,preview);"></asp:FileUpload> </div> <asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="上传" /> <script type="text/javascript"> function setImagePreview(docObj, localImagId, imgObjPreview) { if (docObj.files && docObj.files[0]) { //火狐下,直接设img属性 imgObjPreview.style.display = ‘block‘; imgObjPreview.style.width = ‘200px‘; imgObjPreview.style.height = ‘200px‘; //火狐7以上版本不能用上面的getAsDataURL()方式获取,需要一下方式 imgObjPreview.src = window.URL.createObjectURL(docObj.files[0]); } else { //IE下,使用滤镜 docObj.select(); var imgSrc = document.selection.createRange().text; //必须设置初始大小 localImagId.style.width = "200px"; localImagId.style.height = "200px"; //图片异常的捕捉,防止用户修改后缀来伪造图片 try { localImagId.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)"; localImagId.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = imgSrc; } catch (e) { alert("您上传的图片格式不正确,请重新选择!"); return false; } imgObjPreview.style.display = ‘none‘; document.selection.empty(); } return true; } </script> <br /> </div> </form> </body> </html>
cs代码:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class Default2 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { //1、找到要上传文件的文件名 string name = FileUpload1.FileName.ToString(); //2、处理文件名 string CLname = DateTime.Now.ToString("yyyyMMddHHmmssms")+name; //3、造一个要保存的路径 string path = @"Files\" + CLname; //4、处理路径为绝对路径 string JDpath = Server.MapPath(path); //5、保存 FileUpload1.SaveAs(JDpath); } protected void Button2_Click(object sender, EventArgs e) { //1、找到要上传文件的文件名 string name = FileUpload1.FileName.ToString(); //2、处理文件名 string CLname = DateTime.Now.ToString("yyyyMMddHHmmssms") + name; //3、造一个要保存的路径 string path = @"images\" + CLname; //4、处理路径为绝对路径 string JDpath = Server.MapPath(path); //5、保存 FileUpload1.SaveAs(JDpath); } }
上传后:
时间: 2024-10-11 18:54:37