【问题标题】:How to upload remote file to the POST URL in java?java - 如何将远程文件上传到java中的POST URL?
【发布时间】:2013-10-22 19:57:04
【问题描述】:

我需要使用 POST 或其他选项将 zip 文件上传到 URL。我按照下面的方法成功上传了文件。

String diskFilePath="/tmp/test.zip;
    String urlStr="https://<ip>/nfc/file.zip";

    HttpsURLConnection conn = (HttpsURLConnection) new URL(urlStr).openConnection();
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setChunkedStreamingMode(CHUCK_LEN);
    conn.setRequestMethod(put? "PUT" : "POST"); // Use a post method to write the file.
    conn.setRequestProperty("Connection", "Keep-Alive");
    conn.setRequestProperty("Content-Length", Long.toString(new File(diskFilePath).length()));

    int i=0;
    while(i<1)
    {
        continue;
    }

    BufferedOutputStream bos = new BufferedOutputStream(conn.getOutputStream());

    BufferedInputStream diskis = new BufferedInputStream(new FileInputStream(diskFilePath));
    int bytesAvailable = diskis.available();
    int bufferSize = Math.min(bytesAvailable, CHUCK_LEN);
    byte[] buffer = new byte[bufferSize];

    long totalBytesWritten = 0;
    while (true) 
    {
        int bytesRead = diskis.read(buffer, 0, bufferSize);
        if (bytesRead == -1) 
        {
            //System.out.println("Total bytes written: " + totalBytesWritten);
            break;
        }

        totalBytesWritten += bytesRead;
        bos.write(buffer, 0, bufferSize);
        bos.flush();
    //  System.out.println("Total bytes written: " + totalBytesWritten);
        int progressPercent = (int) (((bytesAlreadyWritten + totalBytesWritten) * 100) / totalBytes);

    }

现在我的 zip 文件位于远程位置,我需要上传 zip 文件而不下载到本地机器。

我需要传递这个网址“https:///file/test.zip”而不是“/tmp/test.zip”

例如,我在机器 A 上执行程序,并且要上传的文件存在于机器 B 中。Webserver 部署在机器 B 中,并暴露 url 以下载 zip 文件。现在我需要传递这个 ZIP 文件 URL 位置来上传,而不是将 zip 文件下载到机器 A,然后传递到上传 URL。

谢谢, 卡莱

【问题讨论】:

    标签: java file-upload


    【解决方案1】:

    “不下载到本地机器”并不是 100% 的意思。

    以下是避免将文件下载到临时本地文件然后上传的方法。 基本方法是从一个 URLConnection (而不是本地文件)读取并写入另一个 URLConnection (就像你已经做的那样)。 首先向sourceString发出请求,所以

    HttpsURLConnection source = (HttpsURLConnection) new URL("https://machine.B/path/to/file.zip").openConnection();
    

    然后保留所有内容,直到您设置 Content-Length 并将其替换为

    conn.setRequestProperty("Content-Length", source.getContentLength());
    

    然后你所要做的就是使用

    InputStream is = source.getInputStream();
    

    而不是您的diskis

    PS:我不明白.available 逻辑的目的,为什么不直接使用 CHUNK_LEN 作为缓冲区大小? PPS:while(i&lt;0) 循环也可以删除;-)

    【讨论】:

    • 非常感谢。它起作用了。我使用了 URLConnection 而不是 HttpsURLConnection。 URL url=new URL("machine.B/path/to/file.zip"); URLConnection source=url.openConnection();
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-11
    • 2012-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-04
    • 2021-10-22
    相关资源
    最近更新 更多