使用 Java 上传到 FTP

2022-01-09 00:00:00 ftp uploading java

我只是想知道是否有一种简单方法可以将小文件上传到 ftp 服务器.我已经查看了 Apache Commons Net 库,但老实说这似乎相当复杂.有没有更简单的方法可以把小文件上传到ftp?

I was just wondering if there was a simple way I could upload a small file to a ftp server. I've checked out Apache Commons Net library but that seems quite complicated to be honest. Is there any simpler way to upload a small file to ftp?

最终使用了 Apache Commons Net Library,并不太难.

Ended up using the Apache Commons Net Library, wasn't too hard.

推荐答案

来自这个链接:使用 URLConnection 类上传文件到 FTP 服务器.无需外部库.

From this link: Upload files to FTP server using URLConnection class. No external library necessary.

String ftpUrl = "ftp://%s:%s@%s/%s;type=i";
String host = "www.myserver.com";
String user = "tom";
String pass = "secret";
String filePath = "E:/Work/Project.zip";
String uploadPath = "/MyProjects/archive/Project.zip";

ftpUrl = String.format(ftpUrl, user, pass, host, uploadPath);
System.out.println("Upload URL: " + ftpUrl);

try {
    URL url = new URL(ftpUrl);
    URLConnection conn = url.openConnection();
    OutputStream outputStream = conn.getOutputStream();
    FileInputStream inputStream = new FileInputStream(filePath);

    byte[] buffer = new byte[BUFFER_SIZE];
    int bytesRead = -1;
    while ((bytesRead = inputStream.read(buffer)) != -1) {
        outputStream.write(buffer, 0, bytesRead);
    }

    inputStream.close();
    outputStream.close();

    System.out.println("File uploaded");
} catch (IOException ex) {
    ex.printStackTrace();
}

相关文章