SharePoint 获取图片,上传图片

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;

using System.IO;
using Microsoft.SharePoint;
using yesinda.yesindakms.sharepoint;


public partial class usercontrol_ImageList : System.Web.UI.UserControl
{
  private string UploadFile()
        {
            String fileToUpload = this.fileUploadPIC.PostedFile.FileName;
            String url = string.Empty;
            String documentLibraryName = "图像";
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite oSite = SPContext.Current.Site)//
                    {
                        using (SPWeb oWeb = oSite.OpenWeb(Request["WebUrl"]))
                        {
                            oWeb.AllowUnsafeUpdates = true;
                            if (!System.IO.File.Exists(fileToUpload))
                                return;
                            String fileName = System.IO.Path.GetFileName(fileToUpload);
                            SPDocumentLibrary myLibrary = oWeb.Lists[documentLibraryName] as SPDocumentLibrary;
                            //SPFolder folder = myLibrary.RootFolder;
                            //IList<string> list = new List<string>();
                            //foreach (SPFolder folder3 in folder.SubFolders)
                            //{
                            //    if (folder3.Name != "")
                            //    {
                            //        if (folder3.Name.IndexOf("_t") == 0)//获取图片
                            //        {
                            //            foreach (SPFile file in folder3.Files)
                            //            {
                            //                list.Add(file.Name);
                            //            }
                            //        }
                            //    }
                              
                            //}
                            //if (list.Contains(fileName))
                            //{
                            //    this.file_error_info.InnerHtml = "文件上传失败,请尝试更改文件名";
                            //    return;
                            //}
                            Boolean replaceExistingFiles = true;
                            FileStream fileStream = File.OpenRead(fileToUpload);
                            url = oWeb.Url.ToString() + "/" + "PublishingImages" + "/" + fileName;
                            // Upload documentPublishingImages
                            SPFile spfile = myLibrary.RootFolder.Files.Add(url, fileStream, replaceExistingFiles);
                            // Commit
                            spfile.Update();
                            myLibrary.Update();
                            oWeb.Update();
                            oWeb.AllowUnsafeUpdates = false;
                            
                        }
                    }
                   
                });
                
            }
            catch (Exception ex)
            {
                this.show_error_info.InnerHtml = "你输入的参数有误,请重新输入!" + ex;
            }
            return url;
        }     public string ReturnValue = String.Empty;     public string FolderPath = "111";     protected void Page_Load(object sender, EventArgs e)     {         if (!IsPostBack)         {             GetFolder();             BindGrid();         }     }     /// <summary>     /// 创建数据源     /// </summary>     /// <returns></returns>     ICollection CreateDataSource()     {         DataTable dt = new DataTable();  //创建一个名为mytable的DataTable对象形         DataColumn dc = new DataColumn();         //创建一个列对象         dc.DataType = System.Type.GetType("System.Int32");  //指定该列的数据类型         dc.AutoIncrement = true;              //该列为自动增涨列         dc.AutoIncrementSeed = 1;          //初始值         dc.AutoIncrementStep = 2;          //增量         dc.Caption = "id";                     //设置列的标题         dc.ColumnName = "序号";       //设置 列集合对象中的列的名称,datagrid中显示该列名.         dc.Unique = true;                      //为此列创建唯一性约         dc.AllowDBNull = false;           //不允许为空         dt.Columns.Add(dc);              //将该列对象加入到表mytable的列集合中         //普通列         DataColumn dc1 = new DataColumn();         dc1.DataType = System.Type.GetType("System.String");         dc1.AllowDBNull = false;         dc1.Caption = "path";         dc1.ColumnName = "路径";         dc1.DefaultValue = 25;         dt.Columns.Add(dc1);         DataColumn dc2 = new DataColumn();         dc2.DataType = System.Type.GetType("System.String");         dc2.AllowDBNull = false;         dc2.Caption = "path";         dc2.ColumnName = "完整路径";         dc2.DefaultValue = 25;         dt.Columns.Add(dc2);         SPSite sps = yesinda.yesindakms.sharepoint.List.ListLib.findParamSite("/sites/TQOA/", this.Context);         sps.AllowUnsafeUpdates = true;         SPWeb spw = sps.OpenWeb();         spw.AllowUnsafeUpdates = true;         SPList list = spw.Lists["图片"];         SPFolder folder = list.RootFolder;         SPFolderCollection folder2 = list.RootFolder.SubFolders;         foreach (SPFolder folder3 in list.RootFolder.SubFolders)         {             if (folder3.Name != "")             {                 if (folder3.Name == "111")                 {                     foreach (SPFile file in folder3.Files)                     {                         if (dt != null)                         {                             DataRow dr = dt.NewRow();                             dr[0] = file.Item.ID;                             dr[1] = file.Name;                             dr[2] = "http://" + sps.HostName + file.ServerRelativeUrl;                             dt.Rows.Add(dr);                         }                     }                 }             }         }         DataView dv = new DataView(dt);         return dv;     }     ///获取图片库下的文件夹     public void GetFolder()     {         SPSite sps = yesinda.yesindakms.sharepoint.List.ListLib.findParamSite("/sites/TQOA/", this.Context);         sps.AllowUnsafeUpdates = true;         SPWeb spw = sps.OpenWeb();         spw.AllowUnsafeUpdates = true;         SPList list = spw.Lists["图片"];         SPFolder folder = list.RootFolder;         foreach (SPFolder folder3 in list.RootFolder.SubFolders)         {             if (folder3.Name.IndexOf("_") != 0)             {                 this.ddlSelect.Items.Add(folder3.Name);             }         }     }     /// <summary>     /// 绑定GridView控件     /// </summary>     public void BindGrid()     {         this.GridView1.DataKeyNames = new string[] { "序号" };         this.GridView1.DataSource = CreateDataSource();         this.GridView1.DataBind();         this.ddlCurrentPage.Items.Clear();         for (int i = 1; i <= this.GridView1.PageCount; i++)         {             this.ddlCurrentPage.Items.Add(i.ToString());         }         if (this.GridView1.PageIndex != 0)         {             this.ddlCurrentPage.SelectedIndex = this.GridView1.PageIndex;         }     }     protected void btnUpImage_Click(object sender, EventArgs e)     {         AddImage();     }     #region  上传图片     //保存图片路径     public static string ImageUrl = String.Empty;     /// <summary>     /// 上传图片到图片库     /// </summary>     public void AddImage()     {         if (File1.Value != "")         {             //上传附件添加到文档库,并返回ID,赋给model.Mattachment             string filename = File1.PostedFile.FileName.Substring(File1.PostedFile.FileName.LastIndexOf("/") + 1);             Stream filedataStream = File1.PostedFile.InputStream;             int dataLen = File1.PostedFile.ContentLength;             string fileType = File1.PostedFile.ContentType;             byte[] fileData = new byte[dataLen];             filedataStream.Read(fileData, 0, dataLen);             SPSite sps = yesinda.yesindakms.sharepoint.List.ListLib.findParamSite("/sites/TQOA/", this.Context);             sps.AllowUnsafeUpdates = true;             SPWeb spw = sps.OpenWeb();             spw.AllowUnsafeUpdates = true;             SPList list = spw.Lists["图片"];             SPFolder folder = list.RootFolder;             SPFolderCollection folder2 = list.RootFolder.SubFolders;             foreach (SPFolder folder3 in list.RootFolder.SubFolders)             {                 if (folder3.Name == "111")                 {                     bool ex = false;                     if (folder.Exists)                     {                         try                         {                             ex = folder3.Files[filename].Exists;                             Response.Write("<script language="javascript">alert('已有相同名称的文件存在');</script>");                             return;                         }                         catch                         {                             folder3.Files.Add(filename, fileData, true);                             ImageUrl = "http://" + sps.HostName + folder3.ServerRelativeUrl + "/" + filename;                         }                     }                 }             }             Response.Write("<script>window.returnValue='" + ImageUrl + "';window.close();</script>");         }     }     #endregion     //全选     protected void CheckAll(object sender, EventArgs e)     {         CheckBox cbx = (CheckBox)sender;         foreach (GridViewRow gvr in GridView1.Rows)         {             CheckBox ch = (CheckBox)gvr.FindControl("ItemCheckBox");             ch.Checked = cbx.Checked;         }     }     /// <summary>     /// 将图片库中的图片插入到文本中     /// </summary>     /// <param name="sender"></param>     /// <param name="e"></param>     protected void btnOutPut_Click(object sender, EventArgs e)     {         SPSite sps = yesinda.yesindakms.sharepoint.List.ListLib.findParamSite("/sites/TQOA/", this.Context);         sps.AllowUnsafeUpdates = true;         SPWeb spw = sps.OpenWeb();         spw.AllowUnsafeUpdates = true;         SPList list = spw.Lists["图片"];         string ReturnString = String.Empty;         foreach (GridViewRow gvr in this.GridView1.Rows)         {             CheckBox ch = (CheckBox)gvr.FindControl("ItemCheckBox");             if (ch.Checked)             {                 SPListItem listcon = list.Items.GetItemById(Convert.ToInt32(GridView1.DataKeys[gvr.RowIndex].Value.ToString()));                 ReturnString += sps.Url + "/" + listcon.Url;             }         }         Response.Write("<script>window.returnValue='" + ReturnString + "';window.close();</script>");     }     protected void radbtnUpload_SelectedIndexChanged(object sender, EventArgs e)     {         if (this.radbtnUpload.SelectedIndex == 0)         {             this.Panel1.Visible = true;             this.Panel2.Visible = false;         }         else         {             this.Panel1.Visible = false;             this.Panel2.Visible = true;         }     }     protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)     {         e.Row.Cells[2].Attributes.Add("style", "display:none");         e.Row.Cells[1].Attributes.Add("style", "display:none");         //滑过GridView控件显示不同颜色         if (e.Row.RowType == DataControlRowType.DataRow)         {             e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#f0ffff';javascript:document.getElementById('imgshow').src='" + e.Row.Cells[2].Text + "';");             e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");         }         this.lblCurrentPage.Text = string.Format("当前第{0}页/总共{1}页", this.GridView1.PageIndex + 1, this.GridView1.PageCount);     }     protected void lnkbtnFrist_Click(object sender, EventArgs e)     {         //显示首页         this.GridView1.PageIndex = 0;         BindGrid();     }     protected void lnkbtnPre_Click(object sender, EventArgs e)     {         //显示上一页         if (this.GridView1.PageIndex > 0)         {             this.GridView1.PageIndex = this.GridView1.PageIndex - 1;             BindGrid();         }     }     protected void lnkbtnNext_Click(object sender, EventArgs e)     {         //显示下一页         if (this.GridView1.PageIndex < this.GridView1.PageCount)         {             this.GridView1.PageIndex = this.GridView1.PageIndex + 1;             BindGrid();         }     }     protected void lnkbtnLast_Click(object sender, EventArgs e)     {         //显示最后一页         this.GridView1.PageIndex = this.GridView1.PageCount;         BindGrid();     } }

posted on 2015-03-26 13:34  !无名之辈  阅读(378)  评论(0)    收藏  举报