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.
Related
How can I upload a PDF file to host via C# so that it is available for download via an adroid app? This is what I have tried, but it does not work. What am I doing wrong?
static void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
string fileName = ((FTPsetting)e.Argument).Filename;
string fullName = ((FTPsetting)e.Argument).FullName;
string username = ((FTPsetting)e.Argument).Username;
string password = ((FTPsetting)e.Argument).Password;
string server = ((FTPsetting)e.Argument).Server;
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri(string.Format("{0}/{1}", server, fileName)));
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(username, password);
Stream ftpstream = request.GetRequestStream();
FileStream fs = File.OpenRead(fullName);
byte[] buffer = new byte[1024];
double total = (double)fs.Length;
int byteread = 0;
double read = 0;
do
{
if (!backgroundWorker.CancellationPending)
{
byteread = fs.Read(buffer, 0, 1024);
ftpstream.Write(buffer, 0, byteread);
read += (double)byteread;
double percontage = read / total * 100;
backgroundWorker.ReportProgress((int)percontage);
}
}
while (byteread != 0);
fs.Close();
ftpstream.Close();
}
static void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
Console.WriteLine("Completed" + e.ProgressPercentage + "%");
}
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;
I'm going in circles searching and reading forums on how to solve this problems. After a day of trying I'm still at a loss how to solve my problem. I'm uploading a file and need to return the % in a a textbox. I'm having no problem with the upload portion and have no problems returning the values using the BackgroundWorker if I include all my code within the same class. However, what I'm doing is calling an ftp class from form1. I need the ftp class to return the percentage to form1 so I can can display in my UI and also need to have the server response codes returned from my ftp class to display in my form1. Everything was working ok before I tried to run this in a BackgroundWorker process, with the exception of course that the UI becomes unresponsive and returns all status messages after upload completed. Heres my code as it stands now. How do I get the percentage from ftp class and pass it back to form1, as well as the server response code once completed?
public partial class Form1 : Form
{
private BackgroundWorker bw = new BackgroundWorker();
private string ftpServer = #"ftp://10.0.0.0";
private string ftpUser = #"user";
private string ftpPass = #"pass";
private string ftpRemoteFile = #"myfile.exe";
private string ftpLocalFile = #"C:\Uploads\file.exe";
public Form1()
{
InitializeComponent();
bw.WorkerReportsProgress = true;
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
}
private void sendButton_Click(object sender, EventArgs e)
{
progressRichTextBox.Text = "Sending";
if (bw.IsBusy != true)
{
bw.RunWorkerAsync();
}
}
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
ftp ftpClient = new ftp(ftpServer, ftpUser, ftpPass);
ftpClient.upload(progressRichTextBox, ftpRemoteFile, ftpLocalFile);
}
private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (!(e.Error == null))
{
this.progressRichTextBox.Text = ("Error: " + e.Error.Message);
}
else
{
this.progressRichTextBox.Text = "Done!";
}
}
private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.progressRichTextBox.Text = (e.ProgressPercentage.ToString() + "%");
}
}
And heres the ftp class:
public void upload(System.Windows.Forms.RichTextBox progressRichTextBox, string remoteFile, string localFile)
{
FileInfo fileInfo = new FileInfo(localFile);
/* Create an FTP Request */
ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + remoteFile);
/* Log in to the FTP Server with the User Name and Password Provided */
ftpRequest.Credentials = new NetworkCredential(user, pass);
/* Specify generic group name for faster upload */
ftpRequest.ConnectionGroupName = "AffiliateUpload";
/* Specify the Type of FTP Request */
ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
/* Server connection options */
ftpRequest.UseBinary = true;
ftpRequest.UsePassive = true;
ftpRequest.KeepAlive = true;
ftpRequest.ContentLength = fileInfo.Length;
/* Buffer for the Data */
byte[] buff = new byte[bufferSize];
int contentLen;
/* Open a File Stream to Read the File for Upload */
FileStream localFileStream = fileInfo.OpenRead();
try
{
// Stream to which the file to be upload is written
ftpStream = ftpRequest.GetRequestStream();
// Read from the file stream 2kb at a time
contentLen = localFileStream.Read(buff, 0, bufferSize);
// Till Stream content ends
while (contentLen != 0)
{
// Write Content from the file stream to the
// FTP Upload Stream
ftpStream.Write(buff, 0, contentLen);
contentLen = localFileStream.Read(buff, 0, bufferSize);
}
// Close the file stream and the Request Stream
ftpStream.Close();
localFileStream.Close();
ftpRequest = null;
}
catch (Exception ex)
{
Console.WriteLine("Failed sending to " + host + "/" + remoteFile + " (" + ex.Message + ")");
}
}
You don't need to update progressRichTextBox in your upload method. Remove that parameter. You need to provide the worker object to your upload method and call worker.ReportProgress on it.
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 ?
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"];