asp.net 图片批量上传预览,在Silverlight页面中读取并滚动显示

简介: Silverlight动态读取图片并滚动显示asp.net页面中图片上传并预览  ...

Silverlight动态读取图片并滚动显示

asp.net页面中图片上传并预览

 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="MultiFileUpload.aspx.cs"
    Inherits="GQGL_MultiFileUpload" %>

<!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 id="Head1" runat="server">
    <title></title>
    <link type="text/css" rel="Stylesheet" href="css/album.css" />
</head>
<body>
    <form id="form1" runat="server">
    <div id="Layout_2">
        <div id="Uploadimg" class="cols_1">
            <div id="AlbumUpload" class="album meat">
                <div class="upLoad" style="text-align: center">
                    <div id="uploadPanel">
                        <div class="divLine">
                            <asp:FileUpload ID="FileUpload1" runat="server" />
                            <asp:Button ID="btnAdd" runat="server" Text="添加文件" OnClick="btnAdd_Click" />
                        </div>
                    </div>
                    <div>
                        <table style="text-align: center">
                            <tr>
                                <td align="center" width="15%">
                                    文<br />
                                    件<br />
                                    列<br />
                                    表<br />
                                    :
                                </td>
                                <td align="center" width="85%">
                                    <asp:ListBox ID="lbxFile" runat="server" Height="145px" Width="300px"></asp:ListBox>
                                </td>
                            </tr>
                        </table>
                    </div>
                    <div class="divLine">
                        <div class="btnUpload">
                            <asp:Button ID="btnDelete" runat="server" Text="删除文件" OnClick="btnDelete_Click" />  
                            <asp:Button ID="btnPost" runat="server" Text="完成上传" OnClick="btnPost_Click" />
                        </div>
                    </div>
                    <p>
                        温馨提示:1、单张图片最大<span>10M</span><br />
                        2、支持<span>jpg</span>,<span>png</span>格式
                    </p>
                </div>
                <div class="upView">
                    <div class="divLine">
                        图片预览:</div>
                    <ul>
                        <li>
                            <div class="p">
                                <img id="img1" alt="" title="暂无图片" src="images/uploadimg_default.jpg" runat="server" /></div>
                            <div class="d" id="preTitle1">
                                1</div>
                        </li>
                        <li>
                            <div class="p">
                                <img id="img2" alt="" title="暂无图片" src="images/uploadimg_default.jpg" runat="server" /></div>
                            <div class="d" id="preTitle2">
                                2</div>
                        </li>
                        <li>
                            <div class="p">
                                <img id="img3" alt="" title="暂无图片" src="images/uploadimg_default.jpg" runat="server" /></div>
                            <div class="d" id="preTitle3">
                                3</div>
                        </li>
                        <li>
                            <div class="p">
                                <img id="img4" alt="" title="暂无图片" src="images/uploadimg_default.jpg" runat="server" /></div>
                            <div class="d" id="preTitle4">
                                4</div>
                        </li>
                        <li>
                            <div class="p">
                                <img id="img5" alt="" title="暂无图片" src="images/uploadimg_default.jpg" runat="server" /></div>
                            <div class="d" id="preTitle5">
                                5</div>
                        </li>
                        <li>
                            <div class="p">
                                <img id="img6" alt="" title="暂无图片" src="images/uploadimg_default.jpg" runat="server" /></div>
                            <div class="d" id="preTitle6">
                                6</div>
                        </li>
                    </ul>
                </div>
                <div id="x" runat="server">
                </div>
            </div>
        </div>
    </div>
    <asp:HiddenField ID="allFileSize" runat="server" Value="0" />
    </form>
</body>
</html>


 

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.Web.UI.HtmlControls;
using System.Drawing;
using USTC;

public partial class GQGL_MultiFileUpload : System.Web.UI.Page
{
    private String folder;
    private String url;
    DM dm = new DM();
    protected void Page_Load(object sender, EventArgs e)
    {
        folder = Server.MapPath("~/ClientBin/image");
        if (!Directory.Exists(folder))
        {
            Directory.CreateDirectory(folder);
        }
    }

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            String guid = Guid.NewGuid().ToString();
            String newFileName = folder + "\\" + guid + Path.GetExtension(FileUpload1.FileName);
            url = Page.ResolveUrl("~") + "ClientBin/image/" + guid + Path.GetExtension(FileUpload1.FileName);
            int totalFileSize = Int32.Parse(allFileSize.Value);
            int fileSize = FileUpload1.PostedFile.ContentLength;
            //此处也可以限制单个文件的大小
            if (totalFileSize + fileSize > 1024 * 1024 * 100)
            {
                Page.ClientScript.RegisterClientScriptBlock(typeof(string), "", @"<script>alert('总上传的文件超过了大小设置 1024 * 1024 !')</script>");
                return;
            }
            if (FileUpload1.FileName.Split('.')[1].ToLower() == "jpg" || FileUpload1.FileName.Split('.')[1].ToLower() == "png")
            {
                FileUpload1.SaveAs(newFileName);
            }
            else
            {
                Page.ClientScript.RegisterClientScriptBlock(typeof(string), "", @"<script>alert('添加的文件格式不正确,确保是jpg或png格式 !')</script>");
                return;
            }
            ListItem item = new ListItem();
            item.Text = FileUpload1.FileName;
            item.Value = url + "|" + newFileName;
            for (int i = 0; i < lbxFile.Items.Count; i++)
            {
                if (lbxFile.Items[i].Text.Equals(FileUpload1.FileName, StringComparison.InvariantCultureIgnoreCase))
                {
                    Page.ClientScript.RegisterClientScriptBlock(typeof(string), "", @"<script>alert('不能添加已经添加过的文件!')</script>");
                    return;
                }
            }
            totalFileSize += fileSize;
            allFileSize.Value = totalFileSize.ToString();
            lbxFile.Items.Add(item);
            PreViewImage();
        }
    }

    protected void btnPost_Click(object sender, EventArgs e)
    {
        //对上传的文件进行进一步处理,或者退出弹出窗口等操作
        for (int i = lbxFile.Items.Count - 1; i > -1; i--)
        {

            //保存图片的同时保存入数据库表
            string depId = Session["depId"].ToString();
            string picUrl = lbxFile.Items[i].Value.Split('|')[1].Substring(lbxFile.Items[i].Value.Split('|')[1].LastIndexOf('\\')+1);
            string description = lbxFile.Items[i].Text.Split('.')[0];
            string strSQL = "insert into 灌区图片(BelongToDepId,PicUrl,PicDescription) values('" + depId + "','" + picUrl + "','" + description + "')";
            dm.execsql(strSQL);
        }
        for (int i = lbxFile.Items.Count - 1; i > -1; i--)
        {
            lbxFile.Items.Remove(lbxFile.Items[i]);
        }
        Page.ClientScript.RegisterClientScriptBlock(typeof(string), "", @"<script>alert('上传成功!')</script>");
    }

    protected void btnDelete_Click(object sender, EventArgs e)
    {
        for (int i = lbxFile.Items.Count - 1; i > -1; i--)
        {
            if (lbxFile.Items[i].Selected)
            {
                String value = lbxFile.Items[i].Value;
                lbxFile.Items.Remove(lbxFile.Items[i]);
                //同时去掉预览中的图片
                string index = "img" + (i + 1);
                (Page.FindControl(index) as HtmlImage).Src = "images/uploadimg_default.jpg";
                (Page.FindControl(index) as HtmlImage).Width = 120;
                (Page.FindControl(index) as HtmlImage).Height = 90;
                (Page.FindControl(index) as HtmlImage).Attributes["title"] = "暂无图片";
                if (File.Exists(value.Split('|')[1]))
                {
                    File.Delete(value.Split('|')[1]);
                }
            }
        }
    }

    private void PreViewImage()
    {
        for (int i = 0; i < lbxFile.Items.Count; i++)
        {
            string index = "img" + (i + 1);
            (Page.FindControl(index) as HtmlImage).Src = lbxFile.Items[i].Value.Split('|')[0];
            (Page.FindControl(index) as HtmlImage).Width = 120;
            (Page.FindControl(index) as HtmlImage).Height = 120;
            (Page.FindControl(index) as HtmlImage).Attributes["title"] = lbxFile.Items[i].Text.Split('.')[0];
        }
    }

}


Silverlight页面展示

<UserControl x:Class="gqfc.SPImageList"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400" Loaded="UserControl_Loaded">
    <Grid x:Name="LayoutRoot" Background="White">
        <Border HorizontalAlignment="Right" Margin="0,25,0,0" Width="170" BorderBrush="#FF0084FF" BorderThickness="1">
    		<StackPanel x:Name="sp" MouseEnter="sp_MouseEnter" MouseLeave="sp_MouseLeave">
    			<Border x:Name="b1" Margin="0,2" BorderBrush="#FF0084FF" BorderThickness="0,1">
    				<Image x:Name="img1" Source="/gqfc;component/Photos/uploadimg_default.jpg" Cursor="Hand" Stretch="Fill" Height="128"/>
    			</Border>
    			<Border x:Name="b2" Margin="0,2" BorderBrush="#FF0084FF" BorderThickness="0,1">
    				<Image x:Name="img2" Source="/gqfc;component/Photos/uploadimg_default.jpg" Cursor="Hand" Stretch="Fill" Height="128"/>
    			</Border>
    			<Border x:Name="b3" Margin="0,2" BorderBrush="#FF0084FF" BorderThickness="0,1">
    				<Image x:Name="img3" Source="/gqfc;component/Photos/uploadimg_default.jpg" Cursor="Hand" Stretch="Fill" Height="128"/>
    			</Border>
    			<Border x:Name="b4" Margin="0,2" BorderBrush="#FF0084FF" BorderThickness="0,1">
    				<Image x:Name="img4" Source="/gqfc;component/Photos/uploadimg_default.jpg" Cursor="Hand" Stretch="Fill" Height="128"/>
    			</Border>
    			<Border x:Name="b5" Margin="0,2" BorderThickness="0,1" BorderBrush="#FF0084FF">
    				<Image x:Name="img5" Source="/gqfc;component/Photos/uploadimg_default.jpg" Cursor="Hand" Stretch="Fill" Height="128"/>
    			</Border>
    			<Border x:Name="b6" Margin="0,2" BorderBrush="#FF0084FF" BorderThickness="0,1">
    				<Image x:Name="img6" Source="/gqfc;component/Photos/uploadimg_default.jpg" Cursor="Hand" Stretch="Fill" Height="128"/>
    			</Border>
    		</StackPanel>
    	</Border>
        <ComboBox x:Name="cbSelectArea" HorizontalAlignment="Right" VerticalAlignment="Top" Width="170" FontSize="13.333" FontFamily="Microsoft YaHei" Height="25" SelectionChanged="cbSelectArea_SelectionChanged"/>
    </Grid>
</UserControl>


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.Windows.Media.Imaging;
using System.Windows.Media.Effects;
using System.Json;
using gqfc.ServiceReference1;
using System.Collections.ObjectModel;

namespace gqfc
{
    public partial class SPImageList : UserControl
    {
        /// <summary>
        /// Json数据源
        /// </summary>
        string imgData = "[{src:'/image/uploadimg_default.jpg',name:'暂无图片'}]";

        int currentIndex = 0;//当前imgData的索引
        int currentImgIndex = 0;//当前第几张小图为阴影区
        int _Max = 6;//右侧显示几张小图

        List<ImageItem> listSrc = new List<ImageItem>();

        private DispatcherTimer _timer;

        public SPImageList()
        {
            InitializeComponent();
        }

        #region 获取部门列表

        /// <summary>
        /// 获取部门列表
        /// </summary>
        public void BindComboBox()
        {
            getDataSoapClient client = new getDataSoapClient();
            client.getDepartmentListCompleted += new EventHandler<getDepartmentListCompletedEventArgs>(client_getDepartmentListCompleted);
            client.getDepartmentListAsync();
        }

        void client_getDepartmentListCompleted(object sender, getDepartmentListCompletedEventArgs e)
        {
            ObservableCollection<Department> lists = e.Result;
            this.cbSelectArea.ItemsSource = lists;
            this.cbSelectArea.DisplayMemberPath = "DepName";
            this.cbSelectArea.UpdateLayout();
            this.cbSelectArea.SelectedIndex = 0;
        }

        #endregion


        private void UserControl_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            //绑定ComboBox
            BindComboBox();

            getDataSoapClient client = new getDataSoapClient();
            client.getAllImageCompleted += new EventHandler<getAllImageCompletedEventArgs>(client_getAllImageCompleted);
            client.getAllImageAsync();

            LoadImageAndScroll();
        }

        void client_getAllImageCompleted(object sender, getAllImageCompletedEventArgs e)
        {
            imgData = e.Result;
            //MessageBox.Show(imgData);
        }

        /// <summary>
        /// 加载图片并滚动显示
        /// </summary>
        public void LoadImageAndScroll()
        {
            currentIndex = 0;
            currentImgIndex = 0;
            LoadImage();

            #region 启动定时器

            _timer = new DispatcherTimer();
            _timer.Interval = new TimeSpan(0, 0, 2);
            _timer.Tick += new EventHandler(_timer_Tick);
            _timer.Start();

            #endregion
        }

        /// <summary>
        /// 加载图片
        /// </summary>
        public void LoadImages()
        {
            currentIndex = 0;
            currentImgIndex = 0;
            LoadImage();
        }

        void _timer_Tick(object sender, EventArgs e)
        {
            down(sender, null);
        }

        /// <summary>
        /// 从下往上滚动的逻辑处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void down(object sender, MouseButtonEventArgs e)
        {
            currentIndex++;
            if (currentIndex >= listSrc.Count)
            {
                currentIndex = 0;
            }
            LoadImage();
        }

        /// <summary>
        /// 加载图片
        /// </summary>
        private void LoadImage()
        {
            listSrc.Clear();
            JsonValue jv = JsonArray.Parse(imgData);
            for (int i = 0; i < jv.Count; i++)
            {
                listSrc.Add(new ImageItem() { src = jv[i]["src"].ToString().Replace("\\/", "/").Replace("\"", ""), name = jv[i]["name"].ToString().Replace("\\/", "/").Replace("\"", "") });
            }

            int _start = currentIndex % listSrc.Count;
            for (int i = 0; i < _Max; i++)
            {
                if (_start >= listSrc.Count)
                {
                    _start = _start % listSrc.Count;
                }
                Image img = this.sp.FindName("img" + (i + 1).ToString()) as Image;
                if (i < listSrc.Count)
                {
                    img.Source = new BitmapImage(new Uri(listSrc[_start].src, UriKind.Relative));
                }
                else
                {
                    img.Source = new BitmapImage(new Uri("/Photos/uploadimg_default.jpg", UriKind.Relative));
                }
                //在这里处理个数问题

                if (i == currentImgIndex)
                {
                    int index = i + 1;
                    //设置对应的Border边框和颜色
                    string tag = "b" + index;
                    (sp.FindName(tag) as Border).BorderBrush = new SolidColorBrush(Colors.Red);
                    (sp.FindName(tag) as Border).BorderThickness = new Thickness(2, 2, 2, 2);
                    //增加阴影效果
                    //DropShadowEffect dse = new DropShadowEffect();
                    //dse.BlurRadius = 10;
                    //dse.ShadowDepth = 10;
                    //dse.Opacity = 0.8;
                    //dse.Direction = 145;
                    //img.Effect = dse;
                }
                else
                {
                    img.Effect = null;
                }
                _start++;
            }

        }

        private void cbSelectArea_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            Department dp = this.cbSelectArea.SelectedItem as Department;
            //获取部门ID
            getDataSoapClient client = new getDataSoapClient();
            client.getImageByDepartmentIDCompleted += new EventHandler<getImageByDepartmentIDCompletedEventArgs>(client_getImageByDepartmentIDCompleted);
            client.getImageByDepartmentIDAsync(dp.DepId);
            //MessageBox.Show(dp.DepId);

        }

        void client_getImageByDepartmentIDCompleted(object sender, getImageByDepartmentIDCompletedEventArgs e)
        {
            //重新赋值
            imgData = e.Result;
            if (imgData == "[]")
            {
                imgData = "[{src:'/image/uploadimg_default.jpg',name:'暂无图片'}]";
            }
            else
            {

            }
            //MessageBox.Show(imgData);
            //载入图片
            LoadImages();
        }

        private void sp_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
        {
            _timer.Stop();
        }

        private void sp_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
        {
            _timer.Start();
        }
    }

    /// <summary>
    /// 自定义类
    /// </summary>
    public class ImageItem
    {
        public string src { set; get; }
        public string name { set; get; }
    }
}

 

相关文章
|
6月前
|
人工智能 缓存 Kubernetes
.NET 9 首个预览版发布:瞄准云原生和智能应用开发
.NET 9 首个预览版发布:瞄准云原生和智能应用开发
|
6月前
|
存储 SQL 开发框架
分享88个ASP贺卡图片源码,总有一款适合您
分享88个ASP贺卡图片源码,总有一款适合您
45 2
|
6月前
|
SQL 存储 开发框架
分享107个ASP贺卡图片源码,总有一款适合您
分享107个ASP贺卡图片源码,总有一款适合您
60 1
|
6月前
|
SQL 开发框架 JavaScript
分享66个ASP贺卡图片源码,总有一款适合您
分享66个ASP贺卡图片源码,总有一款适合您
57 0
|
3月前
|
开发框架 JavaScript 前端开发
揭秘:如何让你的asp.net页面变身交互魔术师——先施展JavaScript咒语,再引发服务器端魔法!
【8月更文挑战第16天】在ASP.NET开发中,处理客户端与服务器交互时,常需先执行客户端验证再提交数据。传统上使用ASP.NET Button控件直接触发服务器事件,但难以插入客户端逻辑。本文对比此法与改进方案:利用HTML按钮及JavaScript手动控制表单提交。后者通过`onclick`事件调用JavaScript函数`SubmitForm()`来检查输入并决定是否提交,增强了灵活性和用户体验,同时确保了服务器端逻辑的执行。
49 5
|
6月前
|
开发框架 .NET 中间件
七天.NET 8操作SQLite入门到实战 - (2)第七天Blazor班级管理页面编写和接口对接
七天.NET 8操作SQLite入门到实战 - (2)第七天Blazor班级管理页面编写和接口对接
145 7
|
3月前
|
开发框架 前端开发 .NET
七天.NET 8操作SQLite入门到实战 - (3)第七天Blazor学生管理页面编写和接口对接
七天.NET 8操作SQLite入门到实战 - (3)第七天Blazor学生管理页面编写和接口对接
|
开发框架 JavaScript 前端开发
.NET 8新预览版本使用 Blazor 组件进行服务器端呈现
.NET 8新预览版本使用 Blazor 组件进行服务器端呈现
220 0
.NET 8新预览版本使用 Blazor 组件进行服务器端呈现
|
开发框架 数据可视化 前端开发
ASP.NET Core MVC+Quartz实现定时任务可视化管理页面
ASP.NET Core MVC+Quartz实现定时任务可视化管理页面
578 0