Uploading image to server and reading the response - c#

I have posted an image file to the server which is having a php file.
I used the following code :
void photoChooserTask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
byte[] sbytedata = ReadToEnd(e.ChosenPhoto);
string s = sbytedata.ToString();
WebClient wc = new WebClient();
Uri u = new Uri("http://example.com/file.php");
wc.OpenWriteCompleted+=new OpenWriteCompletedEventHandler(wc_OpenWriteCompleted);
wc.OpenWriteAsync(u, "POST", sbytedata);
}
}
public static void wc_OpenWriteCompleted(object sender, OpenWriteCompletedEventArgs e)
{
if (e.Error == null)
{
object[] objArr = e.UserState as object[];
byte[] fileContent = e.UserState as byte[];
Stream outputStream = e.Result;
outputStream.Write(fileContent, 0, fileContent.Length);
outputStream.Flush();
outputStream.Close();
string s = e.Result.ToString();
}
}
But how to read the response from the server which returns the image file and how to display that image ?

Related

C# - Amazon Lex chatbot voice input [duplicate]

I have the chatbot client running with text but would now like to change it to voice but I am unsure of how to get the stream from the mic for post. For recording audio I am using NAudio but when sending the memory stream I get an error stating
System.IO.IOException: Cannot close stream until all bytes are
written.
Here is my code:
private void recordAudio()
{
if (memoryStream == null)
memoryStream = new MemoryStream();
sourceStream = new NAudio.Wave.WaveIn();
sourceStream.WaveFormat = new NAudio.Wave.WaveFormat(16000, 1);
waveIn = new NAudio.Wave.WaveInProvider(sourceStream);
waveWriter = new WaveFileWriter(new IgnoreDisposeStream(memoryStream), waveIn.WaveFormat);
sourceStream.DataAvailable += new EventHandler<NAudio.Wave.WaveInEventArgs>(sourceStream_DataAvailable);
buff = new BufferedWaveProvider(waveIn.WaveFormat);
sourceStream.StartRecording();
mytimer.Enabled = true;
}
private void sourceStream_DataAvailable(object sender, NAudio.Wave.WaveInEventArgs e)
{
buff.AddSamples(e.Buffer, 0, e.BytesRecorded);
Console.WriteLine("test");
}
void mytimer_Tick(object sender, EventArgs e)
{
if (sourceStream != null)
{
sourceStream.StopRecording();
waveWriter.Flush();
var amazonLexClient = new AmazonLexClient(Amazon.RegionEndpoint.USEast1);
var amazonPostRequest = new Amazon.Lex.Model.PostContentRequest();
var amazonPostResponse = new Amazon.Lex.Model.PostContentResponse();
amazonPostRequest.BotAlias = "voiceBot";
amazonPostRequest.BotName = "voiceBot";
amazonPostRequest.ContentType = "audio/l16; rate=16000; channels=1";
amazonPostRequest.UserId = "user";
amazonPostRequest.InputStream = memoryStream;
amazonPostRequest.UserId = "test";
try
{
amazonPostResponse = amazonLexClient.PostContent(amazonPostRequest);
Console.WriteLine("Got a response");
}
catch (Exception w)
{
Console.WriteLine("{0} Exception caught.", e);
Console.WriteLine(w.Message);
}
You have to set the Position of your MemoryStream to 0 before you pass it to the post request.
memoryStream.Position = 0;

Cannot get the string result from image C# Windows Form

It's always stop at the end of RawFormat, what did I do wrong?
private void genImgBtn_Click(object sender, EventArgs e)
{
if (pictureBox1.Image != null)
{
Image gambar = pictureBox1.Image;
using (MemoryStream ms = new MemoryStream())
{
gambar.Save(ms,gambar.RawFormat);
byte[] imageBytes = ms.ToArray();
qrtext.Text = Convert.ToBase64String(imageBytes);
}
}
else
{
MessageBox.Show("Silahkan pilih gambar terlebih dahulu");
}
}
The program stops and asks for not giving null value. I don't know what should I do to resolve this.

Uploading an image to FTP server on windows phone

Please Help! I've tried everything, i dont know what else to do. I just want to upload an image that the user chooses from their library to my websever.
I already have a code that uses webclient to upload to a url.
private void OnChoosePicturel(object sender, RoutedEventArgs e)
{
PhotoChooserTask task = new PhotoChooserTask();
task.Completed += task_Completed;
task.Show();
}
private void task_Completed(object sender, PhotoResult e)
{
if (e.TaskResult != TaskResult.OK)
return;
const int BLOCK_SIZE = 4096;
Uri uri = new Uri("URL");
WebClient wc = new WebClient();
NetworkCredential g = new NetworkCredential();
g.UserName = "USERNAME";
g.Password = "PASSWORD";
wc.Credentials = g;
wc.AllowReadStreamBuffering = true;
wc.AllowWriteStreamBuffering = true;
try
{
// what to do when write stream is open
wc.OpenWriteCompleted += (s, args) =>
{
using (BinaryReader br = new BinaryReader(e.ChosenPhoto))
{
using (BinaryWriter bw = new BinaryWriter(args.Result))
{
long bCount = 0;
long fileSize = e.ChosenPhoto.Length;
byte[] bytes = new byte[BLOCK_SIZE];
do
{
bytes = br.ReadBytes(BLOCK_SIZE);
bCount += bytes.Length;
bw.Write(bytes);
} while (bCount < fileSize);
}
}
};
}
catch(Exception t)
{
}
// what to do when writing is complete
wc.WriteStreamClosed += (s, args) =>
{
MessageBox.Show("Send Complete");
};
// Write to the WebClient
wc.OpenWriteAsync(uri, "STOR");
}
The problem is , the webclient class only works for "http" urls, but i need to connect and upload the file to an "ftp" url. How do i do this? Ive tried EVERYTHING. Nothing works.

upload image and save file stream in View State

protected void upload_Click(object sender, EventArgs e)
{
if (Upload.Value !="")
{
System.IO.Stream fs = Upload.PostedFile.InputStream;
img_uploadStream = Upload.PostedFile.InputStream;
System.IO.BinaryReader br = new System.IO.BinaryReader(fs);
Byte[] bytes = CreateThumbnail(br.ReadBytes((Int32)fs.Length),150);
string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
imageField.Src = String.Format("data:{0};base64,{1}", "image/jpeg", base64String);
}
}
After upload the image , Upload.PostedFile.InputStream has set to null value .
I want to save this Input Stream to asp.net View State to reuse .
You can use this code
public Byte[] YourImage
{
get
{
if(ViewState["Key"] != null)
{
return (Byte[]) ViewState["Key"];
}
return null;
}
set
{
ViewState["Key"] = value;
}
}
Set ViewState inside upload_Click:
ViewState["ImageStream"]=Upload.PostedFile.InputStream;
Then you can get your viewstate anywhere within the page where you want to use:
System.IO.Stream fstream=(System.IO.Stream)ViewState["ImageStream"];

Accessing the header in OpenReadCompleted Method on windows phone 8

I have an app that downloads an image to the phone and depending on the image category it will assign it to a news feed. I am using this function:
private static void DownloadImage(string furl, string ids)
{
// Connect Again to the API
WebClient client = new WebClient();
client.Headers["NewsID"] = ids;
string url = "www.xxx.com/image/xyz";
client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
client.OpenReadAsync(new Uri(url));
}
private static void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (e.Error == null && !e.Cancelled)
{
Stream reply = null;
StreamReader s = null;
// i am not able to read the sender who is a webclient to retrieve the information it is always skipping it
WebClient wcd = sender as WebClient;
reply = (Stream)e.Result;
s = new StreamReader(reply);
//Console.WriteLine(s.ReadToEnd());
s.Close();
reply.Close();
if (!myIsolatedStorage.DirectoryExists("ImageCache"))
{
myIsolatedStorage.CreateDirectory("ImageCache");
}
//try
//{//((MS.Internal.InternalMemoryStream)(e.Result)).FinalUri.Segments[2]
var graphImage = e.Result;
Random rand = new Random();
string fileName = string.Format("ImageCache/{0}.jpg", rand.Next());
IsolatedStorageFileStream fileStream = myIsolatedStorage.CreateFile(fileName);
BitmapImage image = new BitmapImage();
image.SetSource(e.Result);
WriteableBitmap wb = new WriteableBitmap(image);
// Encode WriteableBitmap object to a JPEG stream.
Extensions.SaveJpeg(wb, fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
fileStream.Close();
//}
//catch (IsolatedStorageException ex)
//{
//IsolatedStorageException
//Exception handle appropriately for your app
//}
}
}
}
In the OpenReadComplete function which I'm using to download the image, I want to get the newsID from the header, and then assign it to the image before saving it into the database. I can't seem to access the header. Is this possible?
I think you can read it with sender.
WebClient c = (WebClient)sender;
string id = c.Headers["NewsID"];

Categories

Resources