0

I'm trying to upload a file to a webserver. I have seen some code online but i think the code is to extensive and i dont need all that (maybe i'm outrageously wrong). My approach is the following one:

public void upLoadFile(String url, String file_path) throws MalformedURLException, FileNotFoundException {


        try {
            File file = new File(file_path);
            URL u = new URL(url);
            URLConnection conn = u.openConnection();
            conn.setDoOutput(true);     

            DataInputStream stream = new DataInputStream(new FileInputStream(file) );
            byte[] buffer = new byte[(int) file.length()];

            stream.readFully(buffer);
            stream.close();

            DataOutputStream fos = new DataOutputStream(conn.getOutputStream());
            fos.write(buffer);
            fos.flush();
            fos.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

I call that funcion like this:

upLoadFile("http://192.168.1.144/NewFile.txt", "C:\\FileToUpload.txt") 

It is supposed to read bytes from a file and write them down on a file in the webserver. Well, i may be wrong but this should be as simple as this. Right? The problem is that, although i dont get any errors or exceptions, i cant manage to upload the file. Honestly, apache's Logs does not even report an acess or something like that.
Could you please help me?

Thanks in advance

Pedro Neves
  • 354
  • 1
  • 7
  • 23
  • 2
    This isn't how HTTP works. You're not even sending a request. If you want to upload files through the HTTP protocol, you should look into the "PUT" method. Or take a look at [some other questions like this one](http://stackoverflow.com/questions/10719124/how-to-upload-file-to-http-remote-server-using-java) – Jon Lin Jul 09 '14 at 19:31
  • 1
    If you want to upload a file to your own server, use FTP or SCP, or implement an API on your server that receive a file sent using either the POST or PUT method. – Dave Morrissey Jul 09 '14 at 19:35
  • I can't controll server side. I'll look over the hints u gave me ;) – Pedro Neves Jul 09 '14 at 19:55

0 Answers0