0
  • I want to create a visual web part to add images by using upload ASP UI controls
  • And while uploading it should also save relevant metadata like Title and Description

Don't have much experience in creating Visual web-part. So please requesting for relevant links and code snippets.

Thanks for your help in advance.

using Microsoft.SharePoint;
using System;
using System.IO;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

namespace TSInfo_Intranet.File_Upload
{
public partial class File_UploadUserControl : UserControl
{
    string siteURL = "";
    string listTitle = "Company Document";

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
        }
    }

    protected void BtnSave_Click1(object sender, EventArgs e)
    {
        uploadDocument();

    }

    public void uploadDocument()
    {
        if (fuUploadFile.PostedFile != null && fuUploadFile.HasFile)
        {
            try
            {
                SPSite siteCollection = SPContext.Current.Site;
                SPWeb web = SPContext.Current.Web;
                SPList spList = web.Lists.TryGetList(listTitle);
                {
                    {
                        byte[] contents;
                        using (Stream filestream = fuUploadFile.PostedFile.InputStream)
                        {
                            contents = new byte[filestream.Length];
                            filestream.Read(contents, 0, 
                            (int)filestream.Length);
                            filestream.Close();
                            string fileName = Path.GetFileName(fuUploadFile.PostedFile.FileName);
                            string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fuUploadFile.PostedFile.FileName);
                            spList.RootFolder.Files.Add(spList.RootFolder.Url + "/" + fileName, contents, true);
                            spList.Update();
                            SetupMetadata(web,spList,fileName,fileNameWithoutExtension);
                        }
                    }
                }
            }

            catch (Exception ex)
            {

                lblMessage.Text = ex.StackTrace;
                lblCheckMesaage.Text = ex.Message;
            }
        }
        else
        {
            lblMessage.Text = "Select a File";
        }
    }
    public void SetupMetadata(SPWeb spWeb, SPList spList, string title, string fileNameWithoutExtension)
    {
        try
        {
            string fullFilePath = siteURL + spList.RootFolder.Url + "/" + title;
            SPFile newFile = spWeb.GetFile(fullFilePath);
            SPListItem item = spList.Items[newFile.UniqueId];
            item["Title"] = fileNameWithoutExtension;
            item["Language"] = spList.Fields["Language"].GetFieldValue(ddlLanguage.SelectedValue);
            item["Department"] = spList.Fields["Department"].GetFieldValue(ddlDepartment.SelectedValue);
            item.Update();
            spWeb.Update();
          }
        catch (Exception )
        {
            lblMessage.Text = "Error ocuured";             
        }  
    }
}

}

  • Did you try the code demo in the post ? – Jerry_MSFT Jul 8 '19 at 6:10
0

Please follow the code demo below to upload file and set metadata column value in Visual Web Part:

ascx:

<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> 
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> 
<%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
<%@ Register Assembly="Microsoft.SharePoint.Taxonomy, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"
    Namespace="Microsoft.SharePoint.Taxonomy" TagPrefix="cc1" %>
<%@ Import Namespace="Microsoft.SharePoint" %> 
<%@ Register Tagprefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="VisualWebPart1UserControl.ascx.cs" Inherits="VisualWebPartProject3.VisualWebPart1.VisualWebPart1UserControl" %>
<table>
<tr>
    <td>Language:</td>
    <td><asp:DropDownList ID="ddllang" runat="server">
        <asp:ListItem>Select Language</asp:ListItem>
        <asp:ListItem>English</asp:ListItem>
        <asp:ListItem>Hindi</asp:ListItem>
        <asp:ListItem>Kannad</asp:ListItem>
        </asp:DropDownList></td>
</tr>
    <tr>
        <td>Document Type:</td>
        <td><asp:DropDownList ID="ddldoctype" runat="server">
            <asp:ListItem>Select Document Type</asp:ListItem>
            <asp:ListItem>IT</asp:ListItem>
            <asp:ListItem>HR</asp:ListItem>
            <asp:ListItem>FINANCE</asp:ListItem>
            </asp:DropDownList></td>
    </tr>
</table>
<table>
    <tr>
        <td>Select File:</td>
        <td><asp:FileUpload ID="fuUploadFile" runat="server" />  </td>
    </tr>
    <tr>
        <td></td>
        <td><asp:Button ID="btnSave" runat="server" Text="Save" Width="105px" OnClick="BtnSave_Click1" /></td>
    </tr>
    <tr>
        <td><asp:Label ID="lblMessage" runat="server" Text=""></asp:Label></td>
    </tr>
    <tr>
        <td><asp:Label ID="lblCheckMesaage" runat="server" Text=""></asp:Label></td>
    </tr>
</table>

ascx.cs:

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Taxonomy;
using System.IO;

namespace VisualWebPartProject3.VisualWebPart1
{
    public partial class VisualWebPart1UserControl : UserControl
    {
        string siteURL = "http://sp/sites/dev/";
        string listTitle = "Documents";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

            }

        }
        public void SetupMetadata(SPWeb spWeb, SPList spList, string title, string fileName)
        {
            try
            {
                string fullFilePath = siteURL + spList.RootFolder.Url + "/" + fileName;
                SPFile newFile = spWeb.GetFile(fullFilePath);
                newFile.CheckIn("checked in");
                SPListItem item = spList.Items.GetItemById(newFile.Item.ID);
                item.File.CheckOut();
                item["Title"] = fileName;
                item["Language"] = spList.Fields["Language"].GetFieldValue(ddllang.SelectedValue);
                item["Department"] = spList.Fields["Department"].GetFieldValue(ddldoctype.SelectedValue);
                item.Update();
                item.File.CheckIn("checked in");
            }
            catch (Exception ex)
            {
                lblMessage.Text = "Error ocuured";
            }
        }


        public void uploadDocument()
        {
            if (fuUploadFile.PostedFile != null && fuUploadFile.HasFile)
            {
                try
                {
                    SPSite siteCollection = SPContext.Current.Site;
                    SPWeb web = SPContext.Current.Web;
                    SPList spList = web.Lists.TryGetList(listTitle);
                    {
                        {
                            byte[] contents;
                            using (Stream filestream = fuUploadFile.PostedFile.InputStream)
                            {
                                contents = new byte[filestream.Length];
                                filestream.Read(contents, 0, (int)filestream.Length);
                                filestream.Close();

                                string fileName = Path.GetFileName(fuUploadFile.PostedFile.FileName);
                                string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fuUploadFile.PostedFile.FileName);
                                spList.RootFolder.Files.Add(spList.RootFolder.Url + "/" + fileName, contents, true);
                                spList.Update();
                                SetupMetadata(web, spList, listTitle, fileName);
                            }
                        }
                    }
                }

                catch (Exception ex)
                {

                    lblMessage.Text = ex.StackTrace;
                    lblCheckMesaage.Text = ex.Message;
                }
            }
            else
            {
                lblMessage.Text = "Select a File";
            }
        }

        protected void BtnSave_Click1(object sender, EventArgs e)
        {
            uploadDocument();
        }
    }
}

enter image description here

enter image description here

enter image description here

  • Hi Jerry, Since i am in process of doing environment setup i have just reformatted the code which i am going to try. Could you kindly have a look if its OK ? – Sukumar MS Jul 8 '19 at 10:15
  • Never mind, I will test your code in my side tomorrow and will update to your if there is any progress. – Jerry_MSFT Jul 8 '19 at 11:04
  • I will update the code snippet I tested and result capture in the reply for your reference. – Jerry_MSFT Jul 9 '19 at 9:23
  • You can check the code snippet in my post now. – Jerry_MSFT Jul 9 '19 at 9:30
  • Perfect thanks. I will try and let me know – Sukumar MS Jul 9 '19 at 10:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.