Silverlight Image Upload Using WCF service
Wednesday, March 19, 2014 Category : Silverlight 0
step 1 : add a class in your web service project with following details
[DataContract]
public class FilesUploader
{
[DataMember]
public string FileName { get; set; }
[DataMember]
public string FoldersName { get; set; }
[DataMember]
public byte[] Imagestream { get; set; }
public string Upload(FilesUploader image)
{
FileStream fileStream = null;
BinaryWriter writer = null;
try
{
//filePath = HttpContext.Current.Server.MapPath(".") + ConfigurationManager.AppSettings["PictureUploadDirectory"] + image.ImageName;
string location = ConfigurationManager.AppSettings["imageFileLocation"].ToString();
string strFilePath = location + image.FoldersName + "\\" + image.FileName;
if (image.FileName != string.Empty)
{
fileStream = File.Open(strFilePath, FileMode.Create);
writer = new BinaryWriter(fileStream);
writer.Write(image.Imagestream);
}
return OperatioinResult.Success;
}
catch (Exception ex)
{
return OperatioinResult.ERROR + " ~ " + ex.Message;
}
finally
{
if (fileStream != null)
fileStream.Close();
if (writer != null)
writer.Close();
}
}
}
step 2 : add this method in your service operation contracnt
[OperationContract]
public string FilesUploader_UploadFiles(FilesUploader fileByte)
{
//MemoryStream byFile = new MemoryStream(System.Text.Encoding.ASCII.GetBytes(fileByte));
return new FilesUploader().Upload(fileByte);
}
Step 3 : use this service reference in your silverlight clinet project.
OpenFileDialog op = new OpenFileDialog();
op.Filter = "Images (*.jpg, *.png, *.bmp)|*.jpg;*.png;*.bmp";
op.ShowDialog();
if (op.File != null && op.File.Name != "")
{
fileStram = (FileStream)op.File.OpenRead();
byte[] bytes = new byte[fileStram.Length];
fileStram.Read(bytes, 0, (int)fileStram.Length);
FilesUploader fUploader = new FilesUploader();
tempImage = "tempPatientImages" + op.File.Extension;
fUploader.FileName = tempImage;
fUploader.Imagestream = bytes;
fUploader.FoldersName = "PatientImges";
service.FilesUploader_UploadFilesAsync(fUploader);
// service is the object of service provider you need it chage it to your object name.
}