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