asp.net 圖片批量上傳預覽,在Silverlight頁面中讀取並滾動顯示

暖楓無敵發表於2012-07-27

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; }
    }
}

 

相關文章