I want to upload a file from c#.net app to a servlet. I am using webclient.UploadFile() and I have also added some data to the uri (see postData below). Everything seems to work ok except webclient seems to be calling the post and the get within the servlet. Therefore my response = null as the get method returns nothing. Can anyone explain why this is happening? If so is there a better way to complete this? Code is below:
Thanks,
//send metadata and file to the servlet
log.Debug("Create instance of WebClient");
WebClient client = new WebClient();
log.Debug("Get the securityToken");
String securityToken = SecurityToken.getToken();
log.Debug("SecurityToken is set to: " + securityToken);
log.Debug("Create a collection of values");
NameValueCollection querystring = setCollectionValues(m1, securityToken);
log.Debug("Create the postData which will include the securityToken and all metadata");
string postdata = "?";
if (querystring != null)
{
foreach (string key in querystring.Keys)
{
postdata += key + "=" + querystring.Get(key) + "&";
}
}
log.Debug("Create the uri and add the postdata.");
Uri uri = new Uri(url + postdata);
log.Debug("URI is: " + uri.ToString());
//Create streams for request /response
Stream data = null;
StreamReader reader = null;
//try to upload the file to the servlet
try
{
log.Debug("Try Upload file " + file + " to servlet at " + url);
client.UploadFile(uri, "POST", file);
data = client.OpenRead(url);
if (data != null)
{
log.Debug("Response returned from server.");
reader = new StreamReader(data);
saveStatus = reader.ReadToEnd();
Console.Write("Response From Server: " + saveStatus);
}
else
{
log.Debug("Error Accessing the saveServlet");
saveStatus = "Problem with Server. Try Again later";
}
log.Debug("Close the Streams");
reader.Close();
data.Close();
}
catch(WebException e)
{
log.Error("Error with accessing the server / servlet. Error returned is: " + e.Status);
saveStatus = "<ERROR>Error occured while trying to upload file to server.<ERROR>";
}
}
else
{
log.Debug("Client side validation Failed.");
saveStatus = validationStatus;
log.Debug("Set the return String to the validationStatus: " + validationStatus);
}