I have some code that I've used to upload images to SharePoint and it works fine. I now need to expand this code and get an image from a remote URL... I've tried several things but I don't know what I need to do to get the file so I can upload it to a library.
Any help is appreciated.
current code:
string filePath = @"C:\Users\username\Desktop\logo.jpg";
string siteURL = "http://mydevsite.com/";
string libraryName = "SOI_Images";
using (SPSite oSite = new SPSite(siteURL))
{
using (SPWeb oWeb = oSite.OpenWeb())
{
if (!System.IO.File.Exists(filePath))
throw new FileNotFoundException("File not found.", filePath);
SPFolder libFolder = oWeb.Folders[libraryName];
// Prepare to upload
string fileName = System.IO.Path.GetFileName(filePath);
FileStream fileStream = File.OpenRead(filePath);
//Check the existing File out if the Library Requires CheckOut
if (libFolder.RequiresCheckout)
{
try
{
SPFile fileOld = libFolder.Files[fileName];
fileOld.CheckOut();
}
catch { }
}
// Upload document
SPFile spfile = libFolder.Files.Add(fileName, fileStream, true);
// Commit
//myLibrary.Update();
//Check the File in and Publish a Major Version
if (libFolder.RequiresCheckout)
{
spfile.CheckIn("Upload Comment", SPCheckinType.MajorCheckIn);
spfile.Publish("Publish Comment");
}
}
}
This worked like a charm
public static void MyUploadtoSharepoint(string _site, string _ListName, string _ImageURL, string _dateTaken, string _uid, string _userEmail)
{
try
{
SPSite site = new SPSite(_site);
SPWeb web = site.RootWeb;
// SPWeb web = SPContext.Current.Site.RootWeb;
web.AllowUnsafeUpdates = true;
SPList pics = web.Lists[_ListName];
//use WebRequest to create stream
WebRequest reqImg = WebRequest.Create(_ImageURL);
//reqImg.UseDefaultCredentials = true;
WebResponse imgResponse = reqImg.GetResponse();
StreamReader reader = new StreamReader(imgResponse.GetResponseStream());
Hashtable metaData = new Hashtable();
metaData.Add("UserName", _uid);
metaData.Add("DateTaken", _dateTaken);
metaData.Add("userEmail", _userEmail);
using (Image imgOriginal = Image.FromStream(reader.BaseStream, true))
{
MemoryStream mstream = new MemoryStream();
imgOriginal.Save(mstream, imgOriginal.RawFormat);
MemoryStream msNew = null;
using (msNew = new MemoryStream(mstream.GetBuffer(), 0, mstream.GetBuffer().Length))
{
msNew.Write(mstream.GetBuffer(), 0, mstream.GetBuffer().Length);
var files = pics.RootFolder.Files.Add(_uid + ".png", msNew.ToArray(), metaData, true);
files.Item.SystemUpdate(false);
// files.CheckIn("");
}
}
web.AllowUnsafeUpdates = false;
site.Dispose();
web.Dispose();
imgResponse.Close();
reader.Dispose();
}
catch (Exception)
{
//do nothing
}
}