2012-05-16 238 views
0

下午好:我需要將音頻文件(.wav)從客戶端傳輸到服務器。問題是我的代碼運行時沒有錯誤,但文件沒有被傳輸,因爲目標文件夾沒有出現!我希望有人能幫助我..問候!將文件上傳到服務器

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:可能需要創建一個接收文件一個servlet,並將它們複製到該文件夾​​在服務器上,但事實是沒有,我的想法是直接從客戶端發送..

回答

0

您必須創建servlet。另外,沒有任何東西可以接受您的內容並將其保存到目錄中。

幸運的是,您不必親自實施它。採取jakarta file upload

+0

感謝您的信息! – DavidH

0

一看我想你不應該使用DataOutputStream類

看一看這一點。

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(); 
// ... 
+0

感謝您的信息! – DavidH