0

Good afternoon: I need to transfer an audio file (. Wav) from client to server. The problem is that my code runs without errors but the file is not transferred as in the destination folder does not appear! I hope someone can help me .. Greetings!

Código:

try {
        URL pagina = new URL("http://localhost:8081/prueba/audio.wav");
        HttpURLConnection con = (HttpURLConnection) pagina.openConnection();

        con.setDoOutput(true);
        con.setDoInput(true);
        con.setRequestMethod("POST");
        con.setRequestProperty("content-type", "audio/x-wav");
        con.setUseCaches(false);

        con.connect();

        String filename = System.getProperty("user.home") + "\\.vmaudio\\" +                "audio.wav";


        FileInputStream is = new FileInputStream(filename);

        DataOutputStream fos = new DataOutputStream(con.getOutputStream ());


        int fByte;

        int bytesTrasferidos = 0;
        while ((fByte = is.read()) != -1) {
            fos.write(fByte);
            fos.flush();
            bytesTrasferidos++;
        }
        System.out.println("Bytes Transferidos: "+bytesTrasferidos);

        fos.close();
        is.close();
        con.disconnect();


        } catch (MalformedURLException ex) {
        Logger.getLogger(pruebasVarias.class.getName()).log(Level.SEVERE, null, ex);

        } catch (Exception ex) {
        Logger.getLogger(pruebasVarias.class.getName()).log(Level.SEVERE, null, ex);

        }

PD: may need to create a servlet that receives the file and them copy to the folder on the server but the truth is not, my idea was to send it directly from the client ..

DavidH
  • 13
  • 4

2 Answers2

0

You do have to create servlet. Otherewise there is nothing that is ready to accept your content and save it into directory.

Fortunately you do not have to implement it yourself. Take a look on jakarta file upload

AlexR
  • 109,181
  • 14
  • 116
  • 194
0

I guess you should NOT use DataOutputStream

Have a look at this.

Using java.net.URLConnection to fire and handle HTTP requests

 URLConnection connection = new URL(url).openConnection();
 connection.setDoOutput(true); // Triggers POST.
 connection.setRequestProperty("Accept-Charset", charset);
 connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
 OutputStream output = null;
 try {
 output = connection.getOutputStream();
 output.write(query.getBytes(charset));
 } finally {  
    if (output != null) try { output.close(); } catch (IOException logOrIgnore) {}
 }
 InputStream response = connection.getInputStream();
 // ...
Community
  • 1
  • 1
stefan bachert
  • 8,643
  • 3
  • 31
  • 38