Hi I'm able to upload a file to Rest WCF Service along with some parameters, in this example just one.
I tried to pass a Json object as parameter but is not working.
So my question is:
is it possible tu upload a file and at the same time an object just like I do in the following example with a String Parameter?
Thank a lot.
WCF
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "/UploadFile/{filename}/{description}", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Xml)]
Boolean UploadFile(String filename, String description, Stream image);
public Boolean UploadFile(String filename, String description, Stream image)
{
Boolean flgUploaded = false;
try
{
String DocumentFolder = @"C:\Temp";
if (!Directory.Exists(DocumentFolder))
Directory.CreateDirectory(DocumentFolder);
String FileNamePath = Path.Combine(@DocumentFolder, filename);
FileInfo info = new FileInfo(FileNamePath);
if (info.Exists)
info.Delete();
FileStream fileStream = null;
using (fileStream = new FileStream(FileNamePath, FileMode.Create, FileAccess.Write, FileShare.None))
{
const int bufferLen = 1024;
byte[] buffer = new byte[bufferLen];
int count = 0;
while ((count = image.Read(buffer, 0, bufferLen)) > 0)
{
fileStream.Write(buffer, 0, count);
}
fileStream.Close();
image.Close();
}
catch (Exception ex)
{
throw new FaultException<string>(ex.Message);
}
}
catch (Exception ex)
{
String error = ex.ToString();
flgUploaded = false;
}
return flgUploaded;
}
CLIENT
OpenFileDialog upload = new OpenFileDialog();
if (upload.ShowDialog() == DialogResult.OK)
{
Boolean flgOK = false;
String Description = "MY DESCRIPTION"
String url = String.Format("http://{0}/Services/myService.svc/UploadFile/" + Path.GetFileName(NewAllegato.NomeFile) + "/" + "{1}", cmbDBName.Text.Trim(), "Description");
HttpWebRequest httpWebRequest = WebRequest.Create(url) as HttpWebRequest;
httpWebRequest.Method = "POST";
FileStream fst = File.Open(upload.FileName, FileMode.Open);
long imgLn = fst.Length;
fst.Close();
httpWebRequest.ContentLength = imgLn;
using (Stream fileStream = File.OpenRead(upload.FileName))
{
using (Stream requestStream = httpWebRequest.GetRequestStream())
{
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int byteCount = 0;
while ((byteCount = fileStream.Read(buffer, 0, bufferSize)) > 0)
{
requestStream.Write(buffer, 0, byteCount);
}
}
}
WebResponse httpResponse = httpWebRequest.GetResponse();
XmlDocument xmlDoc = new XmlDocument();
XmlNode node = null;
XmlNamespaceManager ns = new XmlNamespaceManager(xmlDoc.NameTable);
ns.AddNamespace("msbld", "http://schemas.microsoft.com/2003/10/Serialization/");
using (StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
Object result = streamReader.ReadToEnd();
xmlDoc.LoadXml(Convert.ToString(result));
node = xmlDoc.SelectSingleNode("/msbld:boolean", ns);
flgOK = Convert.ToBoolean(node.InnerXml);
}
}
return flgOK;