将文件上传到服务器

时间:2012-05-16 18:42:23

标签: java httpurlconnection

下午好:我需要将音频文件(.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,然后将它们复制到服务器上的文件夹,但事实并非如此,我的想法是直接从客户端发送..

2 个答案:

答案 0 :(得分:0)

您必须创建servlet。从根本上说,没有任何东西可以接受你的内容并将其保存到目录中。

幸运的是,您不必自己实施它。看看jakarta file upload

答案 1 :(得分: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();
 // ...