Sunday, 24 July 2016

HTTPHandler in Sharepoint

1.Create empty project
2.Add HTTPHandler class from Teamplate if not exist then create manually
3.Open .asxh file paste the below code as per you project Name and Class name

<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ WebHandler Language="C#" CodeBehind="FileUploader.ashx.cs" Class="SharePointProject1Test.Layouts.SharePointProject1Test.FileUploader" %>

and .ashx.cs code like below


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using Microsoft.SharePoint;
namespace SharePointProject1Test.Layouts.SharePointProject1Test
{
    /// <summary>
    /// Summary description for FileUploader
    /// </summary>
    ///
 
    public class FileUploader : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
         
            if (context.Request.Files.Count > 0)
            {
                HttpFileCollection files = context.Request.Files;
                for (int i = 0; i < files.Count; i++)
                {
                    HttpPostedFile file = files[i];
                    AddFile(file.InputStream,file.FileName);
                 
                }
                context.Response.ContentType = "text/plain";
                context.Response.Write("File Uploaded Successfully!");
            }

        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }



        public static void AddFile(Stream inputStream,string fileName)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate() {

            using (SPSite site = new SPSite("http://siteName"))
            {
                site.AllowUnsafeUpdates = true;
                using (SPWeb web = site.OpenWeb())
                {
                    web.AllowUnsafeUpdates = true;
                    byte[] bytes = StreamToByteArray(inputStream);
                    SPFolder myLibrary = web.Folders["Documents_test"];
                    SPFile spfile = myLibrary.Files.Add(fileName, bytes, true);
                    myLibrary.Update();
                    web.AllowUnsafeUpdates = false;
                }
                site.AllowUnsafeUpdates = false;

            }
            });
        }
        public static byte[] StreamToByteArray(Stream inputStream)
        {
            byte[] bytes = new byte[16384];
            using (MemoryStream memoryStream = new MemoryStream())
            {
                int count;
                while ((count = inputStream.Read(bytes, 0, bytes.Length)) > 0)
                {
                    memoryStream.Write(bytes, 0, count);
                }
                return memoryStream.ToArray();
            }
        }
    }
}



4.In the Solution Explorer, click the .ashx file and in the Properties pane, set the Build Action to Content.
5. In the Solution Explorer, click the .ashx.cs file and in the Properties pane, set the Build Action to Compile.
6. Now we need to Save and Close the solution.
7. Edit the .csproj file and add the following text to a PropertyGroup,

<PropertyGroup>
<TokenReplacementFileExtensions>ashx</TokenReplacementFileExtensions>
</PropertyGroup>

8. and reload your project in Visual Studio.
9. test the HTTPHandler open browser and paste url like below
 http://SiteName/_Layouts/15/SharePointProject1Test/FileUploader.ashx
9. now HTTPHandler will catch the event and give a message
10. To call HTTPHandler in JQuery/JavaScript paste the code in your Visua webpart / applicationpage / in Content Editor Webpart like below

<script src="/_layouts/15/SharePointProject1Test/jquery-1.4.1.min.js"></script>

<script type="text/javascript">
    $(document).ready(function () {
        $("#btnUpload").click(function () {

            uploadfile();


        });
    });

    function uploadfile() {
        var bannerImage = $("#fupload").val();

        if (bannerImage) {
            var file = document.getElementById('fupload').files[0];
            var formData = new FormData();
            formData.append(file.name, file);
            var xhr = new XMLHttpRequest();
            var url = "/_Layouts/15/SharePointProject1Test/FileUploader.ashx";
            xhr.open('POST', url, true);
            xhr.onload = function (e) {
                var response = $.parseJSON(e.target.response);
alert(response);
           
            };

            xhr.send(formData);  // multipart/form-data

        }
    }
</script>

 <h3>Upload file Using HTTPHandler in SharePoint</h3>
    <table>
        <tr>  
        <td>
            <input id="fupload" type="file"/><br />
            </td>
 
        </tr>
        <tr>
 
        <td><input id="btnUpload"  value="Upload Selected File" type="button" /></td>
        </tr>
    </table>


No comments:

Post a Comment