Uploading, Deleting, and Downloading a File from SharePoint 2003 Document Library






3.33/5 (7 votes)
This article demonstrates how to upload, delete, and download a file from SharePoint 2003 Document Library.
Introduction
This article demonstrates how to upload, delete, and download a file from SharePoint 2003 site's Document Library. I have not posted MY solution HERE because it was a bit tricky as I was maintaining some information in my own database too. This would have confused a general user.
Background
I was assigned a project to make a document management system using SharePoint Portal Server. The user's requirement was that the file should be saved in the SharePoint document library and the custom application should be hosted under a SharePoint site only. I Googled around to find a procedure for uploading, deleting, and downloading file from a SharePoint library but none of the code worked in my case; most of the code I found was for SharePoint Server 2007. So I decided to do some research and came up with this code.
Using the code
First of all, you have to include a reference to the Microsoft.SharePoint
library and then include the following namespaces in your code file for accessing SharePoint.
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebPartPages;
using Microsoft.SharePoint.WebControls;
Code for uploading file to document library
// Make an object of your SharePoint site.
// Here sharePointURL is the url of your SharePoint site
SPSite site = new SPSite(sharePointURL);
SPWeb web = site.OpenWeb();
web.AllowUnsafeUpdates=true;
string path ="";
// here filePath is html file control with runat="server"
// being used to pick the file browsed by user
string []fileName =filePath.PostedFile.FileName.Split('\\');
int length = fileName.Length;
// get the name of file from path
string file=fileName[length-1];
// Get the library object where LibraryName is the name of Document Library.
SPFolder folder = web.GetFolder(LibraryName);
//
SPFileCollection files=folder.Files;
// Pick up the file in binary stream
Stream fStream = filePath.PostedFile.InputStream;
// Read file in a byte array
byte[] MyData= new byte[fStream.Length];
fStream.Read(MyData, 0, (int)fStream.Length);
fStream.Close();
SPFile fff= files.Add(file,MyData);
web.AllowUnsafeUpdates=false;
Now if you want, you can maintain an ID at your end the object, fff
would be referring to the uploaded file and you can get the ID of newly uploaded file
as fff.Item.ID
.
In case you have enabled versioning on your document library and a file with same name you are uploading already exists, it will create a version of the existing file and return an object to it; in this case, you get the ID of the existing file.
However, if you have disabled versioning and a file with same name already exists, then you will get an error in uploading the file.
Code for deleting a file from the document library
//Make an object of Site
SPSite site = new SPSite(sharePointURL);
SPWeb web = site.OpenWeb();
web.AllowUnsafeUpdates=true;
//Get the Document Library object
SPFolder folder = web.GetFolder(LibraryName);
//Get the files in the document Library
SPFileCollection files=folder.Files;
//If you dont know the url of file and have maintained only the id of file then
//Loop through all files to get the desired file and then get url from it
for(int i=0; i< files.Count;i++)
{
SPFile tempFile= files[i];
//IdOfFileYouWantToDelete
if(tempFile.Item.ID.ToString()==IdOfFileYouWantToDelete)
{
//if you are maintaing the url of file then you can use this
//directly instead of looping through all objects to get file url
//in that case you just have to pass the url of file intead of tempFile.Url
folder.Files.Delete(tempFile.Url);
}
}
web.AllowUnsafeUpdates=false;
Code for downloading a file from the document library
One method of downloading a file is to provide a direct link to the file in the SharePoint Document Library. Let us say that your site URL is http://xyz, and our document library name is doclib, and the file which you want to download is testFile.doc. Now all you have to do is provide a link targeting the URL of file, which is http://xyz/doclib/testFile.doc. When the user clicks on this link, SharePoint will handle the request and download the file. But in many cases, SharePoint opens the file for editing instead of prompting for download so another technique is to get the file in the byte stream and write it on the response stream.
try
{
int flag=0;
SPSite site = new SPSite(sharePointURL);
SPWeb web = site.OpenWeb();
web.AllowUnsafeUpdates=true;
string strContentType="";
// docLib is the name of document library
SPFolder folder = web.GetFolder("docLib");
SPFileCollection files=folder.Files;
//"docLib" is name of document library and testFile.doc is the name of file
string url=sharePointURL+"/"+"docLib"+"/"+"testFile.doc"
SPFile tempFile = web.GetFile(url);
//Get the extension of File.
string []fext=this.filename[0].Split('.');
byte []obj=(byte[])tempFile.OpenBinary();
// Get the extension of File to determine the file type
string casestring="";
if(fext.Length>1)
{
casestring= fext[fext.Length-1];
}
//set the content type of file according to extension
switch(casestring)
{
case "txt":
strContentType = "text/plain";
break;
case "htm" : strContentType = "text/html";
break;
case "html" : strContentType = "text/html";
break;
case "rtf" : strContentType = "text/richtext";
break;
case "jpg" : strContentType = "image/jpeg";
break;
case "jpeg": strContentType = "image/jpeg";
break;
case "gif" : strContentType = "image/gif";
break;
case "bmp" : strContentType = "image/bmp";
break;
case "mpg" : strContentType = "video/mpeg";
break;
case "mpeg": strContentType = "video/mpeg";
break;
case "avi" : strContentType = "video/avi";
break;
case "pdf" : strContentType = "application/pdf";
break;
case "doc" : strContentType = "application/msword";
break;
case "dot": strContentType = "application/msword";
break;
case "csv" : strContentType = "application/vnd.msexcel";
break;
case ".xls": strContentType = "application/vnd.msexcel";
break;
case ".xlt": strContentType = "application/vnd.msexcel";
break;
default : strContentType = "application/octet-stream";
break;
}
Response.ClearContent();
Response.ClearHeaders();
Response.AppendHeader("Content-Disposition",
"attachment; filename= "+filename[0]);
Response.ContentType = strContentType;
//Check that the client is connected and has
//not closed the connection after the request
if(Response.IsClientConnected)
Response.BinaryWrite(obj);
Response.Flush();
Response.Close();
}
catch(Exception ex)
{
}
Points of interest
SharePoint treats the document library as a folder so we have used this to perform all these tasks. My project required the mapping of documents to my custom categories and there can not be two files with the same name in a category. I was using only one document library and there could not be files with same name in a document library as this will create a version if versioning is enabled, so to make the filename unique, I inserted the category ID in the file name before the extension. This made my file name unique and I was able to upload files with the same name in two different categories and my requirement of a unique file in a category was also met.
For all this code to execute, the currently logged in user should have upload, delete, and download permissions in the respective document library.