I am calling this PHP code from Android to transfer file from Android to server and its working perfectly fine.
<?php
$target_path = "./";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>
But my server application is in .net and I have to write this code in .net
I tried to write .net version code but it does not work and returns 500 internal server error.
public partial class uploadfiles : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
try
{
HttpFileCollection uploadFile = Request.Files;
if (uploadFile.Count > 0)
{
HttpPostedFile postedFile = uploadFile[0];
System.IO.Stream inStream = postedFile.InputStream;
byte[] fileData = new byte[postedFile.ContentLength];
inStream.Read(fileData, 0, postedFile.ContentLength);
postedFile.SaveAs(Server.MapPath("Data") + "\\" + postedFile.FileName);
}
}
catch (Exception ex)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("Message : " +ex.Message);
sb.AppendLine("Source : " + ex.Source);
sb.AppendLine("StackTrace : " + ex.StackTrace);
sb.AppendLine("InnerException : " + ex.InnerException);
sb.AppendLine("ToString : " + ex.ToString());
LogInToFile(sb.ToString());
}
}
}
It does not log any exception or even I think it does not reach to its first line. I checked it through Log file. as it does not work. please help.
Android code is below
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
DataInputStream inputStream = null;
String pathToOurFile = "/data/file_to_send.mp3";
String urlServer = "http://192.168.1.1/handle_upload.php";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
try
{
FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile) );
URL url = new URL(urlServer);
connection = (HttpURLConnection) url.openConnection();
// Allow Inputs & Outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
// Enable POST method
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
outputStream = new DataOutputStream( connection.getOutputStream() );
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathToOurFile +"\"" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = connection.getResponseCode();
serverResponseMessage = connection.getResponseMessage();
fileInputStream.close();
outputStream.flush();
outputStream.close();
}
catch (Exception ex)
{
//Exception handling
}
The default max file size limit in ASP.NET application is 4 MB. You can configure the application to accept bigger size by setting the below in web.config
<system.web>
<httpRuntime maxRequestLength="20480" />
</system.web>
To learn more about configuring the file size limit check out Large file uploads in ASP.NET
Try this:
postedFile.SaveAs(Server.MapPath("~/Data/" + postedFile.FileName ));
where ~/Data/ is the location where you want to save your file.
then + postedFile.FileName your filename.
Best Regards
Related
I am trying to download a file usng FTP within a C# console application, but even though I now the paths are correct I always get an error saying "550 file not found".
Is there any way, to return the current path (once connected to the server)?
// lade datei von FTP server
string ftpfullpath = "ftp://" + Properties.Settings.Default.FTP_Server + Properties.Settings.Default.FTP_Pfad + "/" + Properties.Settings.Default.FTP_Dateiname;
Console.WriteLine("Starte Download von: " + ftpfullpath);
using (WebClient request = new WebClient())
{
request.Credentials = new NetworkCredential(Properties.Settings.Default.FTP_User, Properties.Settings.Default.FTP_Passwort);
byte[] fileData = request.DownloadData(ftpfullpath);
using (FileStream file = File.Create(#path + "/tmp/" + Properties.Settings.Default.FTP_Dateiname))
{
file.Write(fileData, 0, fileData.Length);
file.Close();
}
Console.WriteLine("Download abgeschlossen!");
}
EDIT
My mistake. Fixed the filepath, still getting the same error. But if I connect with FileZilla that's the exact file path.
Finally found a solution by using System.Net.FtpClient (https://netftp.codeplex.com/releases/view/95632) and using the following code.
// aktueller pfad
string apppath = Directory.GetCurrentDirectory();
Console.WriteLine("Bereite Download von FTP Server vor!");
using (var ftpClient = new FtpClient())
{
ftpClient.Host = Properties.Settings.Default.FTP_Server;
ftpClient.Credentials = new NetworkCredential(Properties.Settings.Default.FTP_User, Properties.Settings.Default.FTP_Passwort);
var destinationDirectory = apppath + "\\Input";
ftpClient.Connect();
var destinationPath = string.Format(#"{0}\{1}", destinationDirectory, Properties.Settings.Default.FTP_Dateiname);
Console.WriteLine("Starte Download von " + Properties.Settings.Default.FTP_Dateiname + " nach " + destinationPath);
using (var ftpStream = ftpClient.OpenRead(Properties.Settings.Default.FTP_Pfad + "/" + Properties.Settings.Default.FTP_Dateiname))
using (var fileStream = File.Create(destinationPath , (int)ftpStream.Length))
{
var buffer = new byte[8 * 1024];
int count;
while ((count = ftpStream.Read(buffer, 0, buffer.Length)) > 0)
{
fileStream.Write(buffer, 0, count);
}
}
}
I think your filename is wrong. Your first line writes a different name than what you set to ftpfullpath. You us FTP_Dateiname on the first line but FTP_Pfad when you set ftpfullpath.
To see what's actually happening move your first line after 'string ftpfullpath...')
and change it to Console.WriteLine("Starte Download von: " + ftpfullpath);
I have a problem with tcpclient, I need to send one or more files, so I have an application with server and client, the protocol is this :
1) I send some strings with information about number of files, files name and their sizes, all this with streamwriter.writeline (received from server with the function
streamreader.readline)
2) After these strings I send the files, after each file the server answers to the client with a streamwriter.writeline of "ACK". The file is sent with the
networkstream.write method, and received with networkstream.read.
The problem is that the server reads till the received bytes are equal to the file size, but... despite the client "seems" to send every byte of the file, the server
receives fewer bytes in total! So the application is blocked in this step, the server is waiting for the next bytes and the client is waiting for the string of "ACK"
with the streamreader.readline before to send the next file or just to finish the operation.
I also wanted to check what the server receives, so I print the number of bytes received during the reading cycle , discovering that sometimes the server reads fewer bytes than the buffer size of the stream (fixed to 1024). This should be normal because TCP reads as soon as it can, it should not be the real problem, right? I can't
believe that tcp loses bytes, but I don't know how to resolve.
Here you can find some part of codes :
----SERVER SIDE----------
..........Doing Stuffs.............
//secServer is the TCPListener socket.
this.secSHandler = secServer.AcceptTcpClient();
this.secSHandler.ReceiveBufferSize = 1024;
this.secSHandler.SendBufferSize = 1024;
this.is_connected_now = true;
print("is connected!!! ");
//Taking streams...
this.stream = this.secSHandler.GetStream();
this.sr = new StreamReader(stream);
this.sw = new StreamWriter(stream);
string first = sr.ReadLine();
print("I read + " + first + " .");
int numFiles = 0;
string connType = first.Substring(0, 6);
if (connType.CompareTo("CLIENT") == 0)
{
//SINCR CLIENT -> SERVER
string clipType = first.Substring(7, 4);
if (clipType.CompareTo("FILE") == 0)
{
//CASE RECEIVE FILE
int posSeparator = first.IndexOf('*');
string nFiles = first.Substring(12, first.Length - 13);
numFiles = Convert.ToInt16(nFiles);
string[] fileNames = new string[numFiles];
int[] fileSizes = new int[numFiles];
//TAKE FROM THE CLIENT ALL FILE NAMES AND SIZES
for (int i = 0; i < numFiles; i++)
{
fileNames[i] = sr.ReadLine();
print("Name file : I read " + fileNames[i]);
string dim = sr.ReadLine();
fileSizes[i] = Convert.ToInt32(dim);
print("Size file : I read " + fileSizes[i]);
}
//RECEVING FILES
for (int i = 0; i < numFiles; i++)
{
receive_single_file_1(stream, fileSizes[i], fileNames[i]); //CANNOT GO AFTER THIS POINT
sw.WriteLine("File sent - number " + i);
sw.Flush();
}
}
}
.............Doing others stuffs.............
sr.Close();
sw.Close();
THE FUNCTION RECEIVE SINGLE FILE IS HERE BELOW
public bool receive_single_file_1(NetworkStream netstream, int size, string filename)
{
int sizeToRead = 0;
string f_name = "";
//...f_name is the result of another operation, for the sake of the example i write only the final instruction
f_name = filename;
byte[] RecData = new byte[1024];
int RecBytes = 0;
try
{
int totalrecbytes = 0;
FileStream Fs = new FileStream((tempFold + f_name), FileMode.OpenOrCreate, FileAccess.Write);
//COUNTER OF THE WHILE
int nciclo = 0;
while ((RecBytes = netstream.Read(RecData, 0, 1024)) > 0)
{
//I defined print in another context...
totalrecbytes += RecBytes;
if(RecBytes!=1024)
print("Cycle : "+ nciclo +" Content RecBytes : " + RecBytes + " e RecData.Length : " + RecData.Length + " byte reads : " + totalrecbytes + ".");
Fs.Write(RecData, 0, RecBytes);
if (totalrecbytes >= size)
{
print("Read all bytes " + totalrecbytes + " over " + size + " .");
break;
}
//Refresh the buffer
RecData = new byte[1024];
nciclo++;
}
print("End of transfer. Received " + totalrecbytes + "File :" + filename + " Saved on " + tempFold);
Fs.Close();
}
catch (Exception ex)
{
//Ok here i return false, but i do some other stuff before
return false;
}
return true;
}
----END OF SERVER SIDE--------------
--------CLIENT SIDE--------------
.....DOING STUFFS....
//sw is the streamWriter, Sr the streamReader and the stream is the networkstream
System.Collections.Specialized.StringCollection formats = Clipboard.GetFileDropList();
sw.WriteLine("CLIENT:FILE:" + formats.Count + "*");
sw.Flush();
//Sending to the server filename and relative size
foreach (string filename in formats)
{
//Ok the * has sense in my protocol...ignore it.
sw.WriteLine((Directory.Exists(filename)) ? System.IO.Path.GetFileName(filename) + "*" : System.IO.Path.GetFileName(filename));
sw.Flush();
FileStream Fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
sw.WriteLine(Fs.Length);
sw.Flush();
stream.Flush();
Fs.Close();
}
//Sending files
foreach (string filename in formats)
{
//client_sync is the class that wrap the TcpClient socket
client_sync.send_single_file(stream, filename);
resp = sr.ReadLine();
}
....DOING STUFF AND end of this function...
The send file function is defined in this way :
(note : i take this function from code project some weeks ago)
public void send_single_file(NetworkStream netstream, string filename)
{
//connected is a param of my class
if (!connected) return;
byte[] SendingBuffer = null;
try
{
FileStream Fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
int NoOfPackets = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(Fs.Length) / Convert.ToDouble(this.BufferSize)));
//NOTE: BUFFERSIZE IS 1024
int TotalLength = (int)Fs.Length, CurrentPacketLength = 0;
int bytes_send = 0;
for (int i = 0; i < NoOfPackets; i++)
{
if (TotalLength > this.BufferSize)
{
CurrentPacketLength = this.BufferSize;
TotalLength = TotalLength - CurrentPacketLength;
}
else
CurrentPacketLength = TotalLength;
SendingBuffer = new byte[CurrentPacketLength];
Fs.Read(SendingBuffer, 0, CurrentPacketLength);
netstream.Write(SendingBuffer, 0, SendingBuffer.Length);
bytes_send += CurrentPacketLength;
}
Fs.Close();
}
catch (Exception ex)
{
netstream.Close();
//my function
close_connection();
}
netstream.Flush();
}
---------END OF CLIENT SIDE------
So...someone can help me to escape from this hell??? THX :)
I am trying to build an uploading-method, which uploads a recorded .wav to my server.
The problem is, that the uploading file is just noise and has always the same size.
Can you tell me why this is & how to to fix it?
private void upload()
{
var isoStore = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication();
if (isoStore.FileExists("AudioTest.wav"))
{
System.IO.IsolatedStorage.IsolatedStorageFileStream _data =
isoStore.OpenFile("AudioTest.wav", FileMode.Open);
byte[] fileContent = new byte[_data.Length];
int bytesRead = _data.Read(fileContent, 0, 4096);
string b64 = Convert.ToBase64String(fileContent, 0, 4096);
WebClient wc = new WebClient();
wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
wc.Encoding = System.Text.Encoding.GetEncoding("ISO-8859-1");
wc.UploadStringAsync(new Uri("http://myhost.de/t/upload.php?upload"),
"&contents=" + b64);
wc.UploadStringCompleted += (a, b) =>
{
Debug.WriteLine("Upload done");
};
}
}
and this is the PHP-Side
<?php
echo "Starting upload\n";
if(isset($_GET["upload"]))
{
$contents = $_POST["contents"];
echo $filename;
try
{
$file = fopen("filename.wav", "w");
$input = base64_decode($contents);
fwrite($file, $input);
fclose($file);
}
catch (Exception $e)
{
echo 'Caught exception: ', $e->getMessage(), "\n";
}
}
?>
You are reading and encoding to Base64 and always setting the same size 4096. You might want to try
int bytesRead = _data.Read(fileContent, 0, _data.Length - 1);
string b64 = Convert.ToBase64String(fileContent, 0, _data.Length);
Secondly URL Encode your string due to the fact that base64 can have + signs in it.
wc.UploadStringAsync(new Uri("http://myhost.de/t/upload.php?upload"),
"&contents=" + HttpUtility.UrlEncode(b64));
and on the PHP side
$input = base64_decode(urldecode($contents));
I'm developing a web application for a handheld RFID reader (windows CE),
and I'm trying to send an XML file from the RFID reader to a laptop throgh wireless network or GPRS. The code works properly with "windows form application" on MS visual studio, but when I try to use it with "smart device application" it doesn't work... an error appears for the "ReadAllBytes" method:
System.IO.File dose not contain a definition for ReadAllBytes
Please help me to handle this error.
Thanks.
The code:
private void button1_Click(object sender, EventArgs e)
{
try
{
string IpAddressString = "10.1.1.104";
IPEndPoint ipEnd_client = new
IPEndPoint(IPAddress.Parse(IpAddressString), 5656);
Socket clientSock_client = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.IP);
string fileName = "student.XML";
string filePath =#"My Device\";
fileName = fileName.Replace("\\", "/");
while (fileName.IndexOf("/") > -1)
{
filePath += fileName.Substring(0, fileName.IndexOf("/") + 1);
fileName = fileName.Substring(fileName.IndexOf("/") + 1);
}
byte[] fileNameByte = Encoding.UTF8.GetBytes(fileName);
if (fileNameByte.Length > 5000 * 1024)
{
curMsg_client = "File size is more than 5Mb,
please try with small file.";
MessageBox.Show("File size is more than 5Mb,
please try with small file.");
return;
}
MessageBox.Show("Buffering ...");
string fullPath = filePath + fileName;
byte[] fileData =File.ReadAllBytes(fullPath);
byte[] clientData = new byte[4 + fileNameByte.Length +
fileData.Length];
//byte[] clientData = new byte[4 + fileNameByte.Length];
byte[] fileNameLen = BitConverter.GetBytes(fileNameByte.Length);
fileNameLen.CopyTo(clientData, 0);
fileNameByte.CopyTo(clientData, 4);
fileData.CopyTo(clientData, 4 + fileNameByte.Length);
MessageBox.Show("Connection to server ...");
clientSock_client.Connect(ipEnd_client);
MessageBox.Show("File sending...");
clientSock_client.Send(clientData, 0, clientData.Length, 0);
MessageBox.Show("Disconnecting...");
clientSock_client.Close();
MessageBox.Show ("File [" + fullPath + "] transferred.");
}
catch (Exception ex)
{
if (ex.Message == "No connection could be made
because the target machine actively refused it")
{
MessageBox.Show ("File Sending fail. Because
server not running.");
}
else
{
MessageBox.Show ("File Sending fail." +
ex.Message.ToString());
}
}
}
It's because, as the error states, ReadAllBytes doesn't exist in the Compact Framework. You have to use an overload of Read to get the data.
Something along these lines:
using (var reader = File.OpenRead(filePath))
{
var fileData = new byte[reader.Length];
reader.Read(fileData, 0, fileData.Length);
}
I think I have some memory issue with a function that should download a file from ftp server. The reason that I think it's a memory thing is because it works fine during debug (maybe it gives the garbage collector more time). Yet I thought that the using should solve this...
Just to be clear the function works when called once yet calling it several times in a for loop invokes the err message: 550 The specified network name is no longer available.
Please help
Asaf
private void downloadFile(string sourceFile, string targetFolder)
{
string remoteFile = sourceFile.Replace("\\","//");
string localFolder = targetFolder + "\\" + sourceFile.Substring(sourceFile.LastIndexOf("\\")+1);
string filename = "ftp://" + ftpServerIP + "//" + remoteFile;
FtpWebRequest ftpReq = (FtpWebRequest)WebRequest.Create(filename);
ftpReq.Method = WebRequestMethods.Ftp.DownloadFile;
ftpReq.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
ftpReq.UseBinary = true;
ftpReq.Proxy = null;
ftpReq.KeepAlive = false; //'3. Settings and action
try
{
using (System.Net.FtpWebResponse response = (System.Net.FtpWebResponse)(ftpReq.GetResponse()))
{
using (System.IO.Stream responseStream = response.GetResponseStream())
{
using (System.IO.FileStream fs = new System.IO.FileStream(localFolder, System.IO.FileMode.Create))
{
Byte[] buffer = new byte[2047];
int read = 0;
do
{
read = responseStream.Read(buffer, 0, buffer.Length);
fs.Write(buffer, 0, read);
} while (read == 0);
responseStream.Close();
fs.Flush();
fs.Close();
}
responseStream.Close();
}
response.Close();
}
}
catch (WebException ex)
{
FtpWebResponse response = (FtpWebResponse)ex.Response;
Console.Out.WriteLine(response.StatusDescription);
}
}
There's a bug in the read loop that causes large files to be truncated. Use:
int read;
while ((read = responseStream.Read(buffer, 0, buffer.Length)) != 0)
{
fs.Write(buffer, 0, read);
}
With that change in place I was able to download a number of large files via FTP without encountering exceptions.