SharePoint 2010 ——自定义上传页面与多文件上传解决方案

最近项目遇到一个很麻烦的问题,原以为很容易解决,结果搞了那么久,先开个头,再慢慢写

 

SharePoint 2010 ——自定义上传页面与多文件上传解决方案

1.创建Sharepoint空白项目,创建应用程序页面,创建custom action,

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <CustomAction Description="Customize the upload.aspx file for a document library"
               RegistrationType="List"
                RegistrationId="101"
                GroupId="Permissions"
                Id="05511583-fb44-4eca-817a-45892250da9e"
                Location="Microsoft.SharePoint.ListEdit"
                Sequence="1000"
                Title="Customize Upload Form (TCL SUNJUNLIN)"
                >
    <UrlAction Url="~site/_layouts/Custom.ApplicationPage/SetCustomUploadProperties.aspx?List={ListId}" />
  </CustomAction>
</Elements>

2自定义项目feature.

using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Administration;

namespace Custom.ApplicationPage.Features.CustomApp
{
    /// <summary>
    /// 此类用于处理在激活、停用、安装、卸载和升级功能的过程中引发的事件。
    /// </summary>
    /// <remarks>
    /// 附加到此类的 GUID 可能会在打包期间使用,不应进行修改。
    /// </remarks>

    [Guid("a4314576-6717-47fc-909b-8e692f1d32c1")]
    public class CustomAppEventReceiver : SPFeatureReceiver
    {
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            try
            {
                SPWeb web = properties.Feature.Parent as SPWeb;
                web.CustomUploadPage = "/_layouts/Custom.ApplicationPage/CustomUpload.aspx";
                web.Update();
            }
            catch (Exception ex)
            {
                LogException(ex);
                throw;
            }
        }


        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            try
            {
                SPWeb web = properties.Feature.Parent as SPWeb;
                web.CustomUploadPage = "";
                web.Update();
            }
            catch (Exception ex)
            {
                LogException(ex);
                throw;
            }
        }
        public static void LogException(Exception ex)
        {
            if (ex.InnerException != null)
                LogException(ex.InnerException);
            Log(ex.Message, ex.StackTrace);
        }
        public static void Log(string Message, string StackTrace)
        {
            //log to ULS
            SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("TCL.CustomUpload", TraceSeverity.High, EventSeverity.ErrorCritical), TraceSeverity.Unexpected, Message, StackTrace);
        }
    }
}
View Code

 

3.编写 自定义 上传页面;

  1 <%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
  2 <%@ Import Namespace="Microsoft.SharePoint.ApplicationPages" %>
  3 <%@ Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls"
  4     Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
  5 <%@ Register TagPrefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
  6 <%@ Register TagPrefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
  7 <%@ Import Namespace="Microsoft.SharePoint" %>
  8 <%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
  9 
 10 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CustomUpload.aspx.cs" Inherits="Custom.ApplicationPage.Layouts.CustomUpload"
 11     DynamicMasterPageFile="~masterurl/default.master" %>
 12 
 13 <asp:Content ID="PageHead" ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
 14     <link   href="/_layouts/Custom.ApplicationPage/JS/uploadify.css" rel="stylesheet" type="text/css" />
 15     <script type="text/javascript" src="/_layouts/Custom.ApplicationPage/JS/jquery-1.9.1.min.js" ></script>
 16     <script type="text/javascript" src="/_layouts/Custom.ApplicationPage/JS/jquery.uploadify.js"></script>
 17 
 18     
 19   <script type="text/javascript">
 20       $(document).ready(function () {
 21           var filelist = "";
 22           var currentDocLib = $("#<%=hiddenCurrentDocLib.ClientID %>").val();
 23           var listID = "";
 24           if (currentDocLib != "" && currentDocLib != null) {
 25 
 26               listID = currentDocLib.substring(currentDocLib.indexOf('{') + 1, currentDocLib.lastIndexOf('}'));
 27           }
 28           $("#uploadify").uploadify({
 29               'swf': '/_layouts/Custom.ApplicationPage/JS/uploadify.swf',
 30               'uploader': '/_layouts/Custom.ApplicationPage/FilesHandler.ashx?listID=' + listID,
 31               'cancelImg': '/_layouts/Custom.ApplicationPage/JS/uploadify-cancel.png',
 32               'buttonText': '选择文件...',
 33               'auto': false,
 34               'multi': true,
 35               'onSelect': function (file) {
 36 
 37                   var mycars = new Array()
 38                   mycars[0] = "\\"
 39                   mycars[1] = "/"
 40                   mycars[2] = ":"
 41                   mycars[3] = "*"
 42                   mycars[4] = "?"
 43                   mycars[5] = "\""
 44                   mycars[6] = "<"
 45                   mycars[7] = ">"
 46                   mycars[8] = "|"
 47                   mycars[9] = "#"
 48                   mycars[10] = "{"
 49                   mycars[11] = "}"
 50                   mycars[12] = "%"
 51                   mycars[13] = "~"
 52                   mycars[14] = "&"
 53 
 54                   for (i = 0; i < mycars.length; i++) {
 55                       var name = file.name;
 56                       if (name.indexOf(mycars[i]) != -1 && name != null) {
 57                           filelist = filelist + " \n " + name;
 58                       }
 59                   }
 60                   $("#<%=hidNotAllowFile.ClientID %>").val(filelist);
 61               },
 62               'onQueueComplete': function (queueData) {
 63 
 64                   window.frameElement.commitPopup();
 65               },
 66               'onDialogClose': function (queueData) {
 67                   var notAllowFile = $("#<%=hidNotAllowFile.ClientID %>").val();
 68                   if (notAllowFile != "" && notAllowFile != null) {
 69                       alert(notAllowFile + '\n文件名包含非法字符,系统将自动替换为合法字符');
 70 
 71                   }               
 72                   filelist = "";
 73               }
 74 
 75 
 76           });
 77       });  
 78     </script>
 79 </asp:Content>
 80 <asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server" >
 81 <div style="width:100%; height:300px;">
 82     <div id="fileQueue">
 83     </div>
 84     <input type="file" name="uploadify" id="uploadify" />
 85     <p style="text-align:right">
 86          <a href="javascript:$('#uploadify').uploadify('upload', '*')">上传</a>
 87            &nbsp; &nbsp;  
 88         <a href="javascript:$('#uploadify').uploadify('cancel', '*')">取消</a>
 89     </p>
 90  
 91    <asp:HiddenField ID="hidNotAllowFile" runat="server" />
 92 
 93    <asp:HiddenField ID="hiddenCurrentDocLib" runat="server" />
 94     </div>
 95 </asp:Content>
 96 <asp:Content ID="PageTitle" ContentPlaceHolderID="PlaceHolderPageTitle" runat="server">
 97     多文件上传 
 98 </asp:Content>
 99 <asp:Content ID="PageTitleInTitleArea" ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea"
100     runat="server">
101     我的应用程序页上传文档
102 </asp:Content>
View Code

 

4.应用Uploadfiy上传插件

5.编写上传服务FilesHandler.ashx,这个文件需要手动创建,找不到这个模板,

 

参考:http://cn.bing.com/search?q=SharePoint%E9%A1%B9%E7%9B%AE%E4%B8%AD%E5%88%9B%E5%BB%BAHttpHandler+.&form=IE10TR&src=IE10TR&pc=LNJB 

using System.Web;
using System.Runtime.InteropServices;
using System;
using System.IO;
using Microsoft.SharePoint;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Collections;

namespace Custom.ApplicationPage.Layouts.Custom.ApplicationPage
{
    [Guid("26c725b1-07d3-4326-ab6b-7343abe0a7ed")]
    public class FilesHandler : IHttpHandler
    {
        public bool IsReusable
        {
            get { return true; }
        }
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            context.Response.Charset = "utf-8";
            string listID = "";
            if (context.Request.QueryString["listID"] != null && !string.IsNullOrEmpty(context.Request.QueryString["listID"].ToString()))
            {
                listID = context.Request.QueryString["listID"];
             
            }
    

            HttpPostedFile file = context.Request.Files["Filedata"];
            string uploadPath =
                HttpContext.Current.Server.MapPath(@context.Request["folder"]) + "\\";
            if (file != null)
            {
                if (!Directory.Exists(uploadPath))
                {
                    Directory.CreateDirectory(uploadPath);
                }
                //file.SaveAs(uploadPath + file.FileName);
                OnSumitToMOSS(file, context, listID);
                //下面这句代码缺少的话,上传成功后上传队列的显示不会自动消失
                context.Response.Write("1");
            }
            else
            {
                context.Response.Write("0");
            }
        }
        public void OnSumitToMOSS(HttpPostedFile postedFile,HttpContext context,string listID)
        {
            try
            {
                using (SPSite site = SPContext.Current.Site)
                {
                 
                    
                    using (SPWeb web = site.OpenWeb())
                    {
                        web.AllowUnsafeUpdates = true;//关闭页面安全性验证    
                        Guid gid=new Guid(listID);
                        SPDocumentLibrary docLib = (SPDocumentLibrary)web.Lists[gid];
                        //SPDocumentLibrary docLib = (SPDocumentLibrary)web.GetList("http://moss:9527/DocLib");
                        ///'检查文件扩展名字
                        if (postedFile != null)
                        {
                            string fileName = postedFile.FileName;
                            if (!string.IsNullOrEmpty(fileName))
                            {
 
                                ArrayList myChar = new ArrayList();
                                myChar.Add("\\");
                                myChar.Add( "/");
                                myChar.Add( ":");
                                myChar.Add( "*");
                                myChar.Add( "?");
                                myChar.Add( "\"");
                                myChar.Add( "<");
                                myChar.Add( ">");
                                myChar.Add( "|");
                                myChar.Add( "#");
                                myChar.Add( "{");
                                myChar.Add( "}");
                                myChar.Add( "%");
                                myChar.Add( "~");
                                myChar.Add( "&");

                                foreach (string str in myChar)
                                {
                                    if (fileName.IndexOf(str) != -1)
                                    {
                                      fileName= fileName.Replace(str, "_");
                                    }
                                }              

                                SPFile file = docLib.RootFolder.Files.Add(fileName, postedFile.InputStream);//向文档库根目录添加文件
                                file.Update();//保存文件
                                docLib.Update();
                                web.Update();
                            }
                        }
                        web.AllowUnsafeUpdates = false;//上传完毕重新开启页面安全性验证
                        //this.Context.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup();</script>");

                    }
                }
            }
            catch (System.Exception Ex)
            {
                context.Response.Write("<script type='text/javascript'>alert(" + Ex.Message + ");</script>");
            }
        }


   

    }
}
View Code

 

posted on 2014-09-19 23:04  SUNJUNLIN  阅读(2597)  评论(0编辑  收藏  举报

导航