昨天发布了一篇 图片上传和显示 的文章,点击"上传"按钮后才能上传和显示图片,这样交互性不太好,所以今天研究了下怎么自动上传和显示,其实也不太复杂,就是利用js,效果图如下:
然后下面是主要代码,上传图片和显示的代码还是昨天那些,具体参考图片上传和显示:
1.界面代码
UploadPic.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="UploadPic.aspx.cs" Inherits="Pic_Try.UploadPic" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ".w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns=".w3.org/1999/xhtml">
<head runat="server">
<title>图片自动上传和显示</title>
<link href="css/uploadpic.css" rel="Stylesheet" type="text/css" />
</head>
<body>
<form id="form1" runat="server">
<div class="pic_image"><asp:Image class="picshow" ID="pic" runat="server" /></div>
<div>
<div class="file_div">
<asp:FileUpload ID="pic_upload" runat="server" ToolTip="选择图片" onchange="javascript:__doPostBack('lbUploadPhoto','')"/>
<span id="file_text">选择图片</span>
</div>
<asp:LinkButton ID="lbUploadPhoto" runat="server" onclick="lbUploadPhoto_Click"></asp:LinkButton>
<asp:Label ID="lbl_pic" runat="server" class="pic_text"></asp:Label></div>
<div class="pic_label">上传图片格式为。jpg, .gif, .bmp,.png,图片大小不得超过8M</div>
</form>
</body>
</html>
2.后台代码
UploadPic.aspx.cs
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)
{
}
/// <summary>
/// 控件事件
/// </summary>
protected void lbUploadPhoto_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)
{
//对上传文件的大小进行检测,限定文件最大不超过8M
if (pic_upload.PostedFile.ContentLength < 8192000)
{
发表回复