Upload and Insert Images to SharePoint 2007 Content Pages - The Easy Way

One of the great new features in SharePoint 2010 is the Ribbon, which offers sets of commands that help you to complete a task. One of these tasks is an easy and quick way to insert an images from your computer into SharePoint pages. In this article, I will show you how to create a similar functionality for SharePoint 2007.

SharePoint 2010 Functionality

First lets see how it works in SharePoint 2010. To insert image from your local computer in SharePoint 2010, you simply press on the Insert Tab in the Ribbon, then on the Picture button you select From Computer.

Then the popup screen “Select Picture” appears. You click on the Browse button to select the image. Then, select the library where the image will be stored.

SharePoint 2007


Now let’s implement it in our SharePoint 2007 environment. Follow these steps to create the same functionality:

Step 1 - Add the “Picture From Computer” Button to the HTML Editor

Save this XML code as RTE2ToolbarExtension.xml and upload in to the http://yoursite/_catalogs/masterpage/Editing Menu/ folder, Check it in, Publish and approve the file.

This XML file defines the new button in the HTML Editor

<?xml version="1.0" encoding="utf-8" ?>

<RTE2ToolbarExtensions>

<RTE2ToolbarExtraButton id="extraUploadImageButtonId"

src="RTE2ToolbarExtraUploadImageButton.js" />

</RTE2ToolbarExtensions>

Save this JavaScript code as RTE2ToolbarExtraUploadImageButton.js and place it in to the C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS\1033 folder

RTE2_RegisterToolbarButton("extraUploadImageButtonId",

"/_layouts/images/OISWEB.GIF",

"Picture From Computer",

"Image Upload",

UploadImageOnClick,

UploadImageResetState,

new Array());

function UploadImageOnClick(strBaseElementID, args) {

var leftPosition = (screen.width) ? (screen.width - 526) / 2 : 100;

var topPosition = (screen.height) ? (screen.height - 300) / 2 : 100;

window.open('/_layouts/UploadImage.aspx?source=' + window.location + '&strBaseElementID=' + strBaseElementID, 'upload', 'width=526,height=300,top=' + topPosition + ',left=' + leftPosition + ',scrollbars=no,location=no,directories=no,status=no,menubar=no,toolbar=no,resizable=no');

RTE_RestoreSelection(strBaseElementID);

return true;

}

function UploadImageResetState(strBaseElementID, args) {

var docEditor = RTE_GetEditorDocument(strBaseElementID);

if (docEditor == null) { return; }

RTE_RestoreSelection(strBaseElementID);

if (docEditor.selection.createRange().text.length != 0) {

RTE_TB_SetEnabledFromCondition(strBaseElementID, true, "extraUploadImageButtonId");

} else {

RTE_TB_SetEnabledFromCondition(strBaseElementID, true, "extraUploadImageButtonId");

}

return true;

}

Step 2 – Create the popup screen “Select Picture” UI

The Select Picture window contains three ASP controls (FileUpload, DropDownList and Checkbox) and one control to validate the images file types.

<table cellpadding="0" cellspacing="0" border="0" width="100%">

<tr>

<td valign="center" id="onetidPageTitleAreaFrame" class='ms-areaseparator' style="height: 40px"

nowrap width="100%">

<table>

<tr>

<td id="onetidPageTitle" class="ms-pagetitle" width="100%" nowrap>

<h1 class="ms-pagetitle">

Select Picture

</h1>

</td>

</tr>

</table>

</td>

</tr>

</table>

<table cellpadding="0" cellspacing="0" width="100%">

<tr>

<td class="ms-descriptiontext" valign="top" style="width: 250px">

<table cellspacing="5" cellpadding="5" width="250" border="0">

<tbody>

<tr>

<td class="ms-descriptiontext ms-inputformdescription">

Upload to:

</td>

<td>

</td>

</tr>

</tbody>

</table>

</td>

<td class="ms-authoringcontrols ms-inputformcontrols" valign="top" align="left">

<table cellspacing="5" cellpadding="5" width="100%" border="0">

<tbody>

<tr>

<td>

<asp:DropDownList CssClass="ms-fileinput" ID="listDropDownList" runat="server" />

</td>

</tr>

</tbody>

</table>

</td>

</tr>

<tr>

<td class="ms-descriptiontext" valign="top" style="width: 250px">

<table cellspacing="5" cellpadding="5" width="250" border="0">

<tbody>

<tr>

<td class="ms-descriptiontext ms-inputformdescription">

Name:

</td>

<td>

</td>

</tr>

</tbody>

</table>

</td>

<td class="ms-authoringcontrols ms-inputformcontrols" valign="top" align="left">

<table cellspacing="5" cellpadding="5" width="100%" border="0">

<tbody>

<tr>

<td>

<asp:FileUpload CssClass="ms-fileinput" ID="File1" runat="server" />

<br />

<asp:Label ID="lblErrorMsg" ForeColor="Red" runat="server"></asp:Label>

<asp:CustomValidator ID="CustomValidator1" runat="server" ClientValidationFunction="ValidateFileUpload"

ErrorMessage="The file you selected is not a valid image file"></asp:CustomValidator>

<asp:Label ID="javascriptCode" runat="server"></asp:Label>

</td>

</tr>

<tr>

<td class="ms-descriptiontext ms-inputformdescription">

<asp:CheckBox runat="server" Checked="true" ID="cbNewVersion" Text="Overwrite existing files" />

</td>

</tr>

</tbody>

</table>

</td>

</tr>

<tr>

<td class="ms-descriptiontext" style="border-top: solid 2px gray" colspan="2">

<img height="10" alt="" src="/_layouts/images/blank.gif" width="1" />

<asp:Label ID="lblUploadErrorMsg" ForeColor="Red" runat="server"></asp:Label>

</td>

</tr>

<tr>

<td>

</td>

<td align="right">

<table cellspacing="5" cellpadding="5" width="100%" border="0">

<tbody>

<tr>

<td>

<table cellspacing="0" cellpadding="0" width="100%">

<colgroup>

<col width="99%" />

<col width="1%" />

</colgroup>

<tbody>

<tr>

<td>

</td>

<td nowrap>

<asp:Button ID="btnUpload" CssClass="ms-ButtonHeightWidth" Text="OK" runat="server"

OnClick="UploadImage" />

<input class="ms-ButtonHeightWidth" id="BtnCancel" onclick="window.close();" type="button"

name="BtnCancel" value="Cancel" />

</td>

</tr>

</tbody>

</table>

</td>

</tr>

</tbody>

</table>

</td>

</tr>

</table>

Step 3 – Create the popup screen “Select Picture” Code Behind

In the Load_Page method we collect the available lists to store the images and we use an upload function to store the image in the list.

protected override void OnLoad(EventArgs e)

{

if (!Page.IsPostBack)

{

lblErrorMsg.Text = "";

lblUploadErrorMsg.Text = "";

string webUrl = string.Empty;

string url = string.Empty;

listDropDownList.Items.Clear();

webUrl = SPContext.Current.Web.Url;

foreach (SPList list in SPContext.Current.Web.Lists)

{

if ((list.BaseTemplate == SPListTemplateType.DocumentLibrary

|| list.BaseTemplate == SPListTemplateType.PictureLibrary)

&& list.Hidden == false)

{

listDropDownList.Items.Add(new ListItem(list.Title, webUrl + "/" + list.RootFolder.Url + "/"));

if (list.RootFolder.Url == "PublishingImages")

{

listDropDownList.SelectedValue = webUrl + "/" + list.RootFolder.Url + "/";

}

}

}

}

}

protected void UploadImage(object sender, EventArgs e)

{

if (File1.PostedFile.FileName == "")

{

lblErrorMsg.Text = "";

}

else

{

string siteUrl = SPContext.Current.Web.Url + "/";

string fileName = System.IO.Path.GetFileName(File1.PostedFile.FileName);

if (!cbNewVersion.Checked)

{

fileName = System.IO.Path.GetFileNameWithoutExtension(File1.PostedFile.FileName);

fileName += "_" + Guid.NewGuid().ToString().Replace("-", "").Substring(1, 6);

fileName += System.IO.Path.GetExtension(File1.PostedFile.FileName);

}
string serverLocation = "c:\\temp\\";
File1.PostedFile.SaveAs(serverLocation + fileName);
bool
isUploaded = UploadFileToList(serverLocation + fileName, listDropDownList.SelectedValue + fileName);

if (isUploaded)

{

string javascriptCodeStr = "<script language=\"JavaScript\" >";

javascriptCodeStr += "var editor = window.opener.document.getElementById(\"" + this.Page.Request.QueryString["strBaseElementID"].ToString() + "\");\n";

javascriptCodeStr += "editor.innerHTML = editor.innerHTML + \"<img src=" + listDropDownList.SelectedValue + fileName + " />\";\n";

javascriptCodeStr += "window.close();\n";

javascriptCodeStr += "<" + "/" + "script>";

javascriptCode.Text = javascriptCodeStr;

}

}

}

public bool UploadFileToList(string sourceFilePath, string targetDocumentLibraryPath)

{

bool success = true;

try

{

System.Net.WebRequest request = System.Net.WebRequest.Create(targetDocumentLibraryPath);

request.Credentials = System.Net.CredentialCache.DefaultCredentials;

request.Method = "PUT";

byte[] fileBuffer = new byte[1024];

using (Stream stream = request.GetRequestStream())

{

using (FileStream fsWorkbook = File.Open(sourceFilePath, FileMode.Open, FileAccess.Read))

{

int startBuffer = fsWorkbook.Read(fileBuffer, 0, fileBuffer.Length);

for (int i = startBuffer; i > 0; i = fsWorkbook.Read(fileBuffer, 0, fileBuffer.Length))

{

stream.Write(fileBuffer, 0, i);

}

}

}

System.Net.WebResponse response = request.GetResponse();

response.Close();

}

catch (Exception ex)

{

success = false;

lblUploadErrorMsg.Text = ex.Message;

}

return success;

}

Step 4 – Deploy

1. Save this complete ASPX page into C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS folder

2. Save this JavaScript file into C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS\1033 folder

3. Upload this XML file to your site in the "master page gallery" in folder "Editing Menu" http://yoursite/_catalogs/masterpage/Editing Menu/
or Site Settings > Galleries > Master Pages > Editing Menu

After you upload the filt Check In --> Publish Major Version-- > and Approve

4. IISRESET and you are ready to go

By Alon Havivi   Popularity  (7228 Views)
Picture
Biography - Alon Havivi

Alon Havivi is a Microsoft Certified Technology Specialist, working as SharePoint Consultant / Developer at e-office. Specialized in SharePoint 2007/2010 and SharePoint Online (Office 365). With more than 10 years of experience in analysis, design and development complex Internet and Intranet portals using the latest Microsoft tools and practices, such as C# .NET 4.0, Silverlight and Windows Azure platform. Besides professional work, I write articles/blog and publish open source projects on CodePlex
View Alon Havivi's professional profile on LinkedIn. View Alon Havivi's projects on CodePlex. View Alon Havivi's articels on Eggheadcafe. Follow Alon Havivi on Twitter Connect with Alon Havivi via Facebook View Alon Havivi's Blog Subscribe to Alon Havivi RSS Feed