以下是一个基本的 Java 文件上传示例,使用 HttpURLConnection 类实现文件上传:

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class FileUploader {
    public static void main(String[] args) throws IOException {
        String fileUrl = 'http://example.com/upload.php'; // 上传文件的URL
        String filePath = '/path/to/file.txt'; // 要上传的文件路径

        File file = new File(filePath);
        if (!file.exists()) {
            System.out.println('文件不存在:' + filePath);
            return;
        }

        HttpURLConnection conn = (HttpURLConnection) new URL(fileUrl).openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod('POST');
        conn.setRequestProperty('Content-Type', 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW');

        OutputStream out = conn.getOutputStream();
        out.write(('\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\n' +
                   'Content-Disposition: form-data; name=\'file\'; filename=\'' + file.getName() + '\'
\n' +
                   'Content-Type: application/octet-stream\r\n\r\n').getBytes());

        InputStream in = FileUploader.class.getResourceAsStream(filePath);
        byte[] buffer = new byte[1024];
        int len = -1;
        while ((len = in.read(buffer)) != -1) {
            out.write(buffer, 0, len);
        }

        out.write('\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--\r\n'.getBytes());
        out.flush();
        out.close();

        int respCode = conn.getResponseCode();
        if (respCode == HttpURLConnection.HTTP_OK) {
            System.out.println('文件上传成功');
        } else {
            System.out.println('文件上传失败:' + conn.getResponseMessage());
        }
    }
}

在这个示例中,我们使用 HttpURLConnection 类来建立 HTTP 连接,并将 Content-Type 设置为 multipart/form-data,以告诉服务器该请求是一个文件上传请求。我们还需要使用一个分隔符来标记文件的开始和结束位置。在本例中,我们使用了 WebKitFormBoundary7MA4YWxkTrZu0gW 作为分隔符。

然后,我们将文件的内容写入连接的输出流中,并在文件内容之前和之后加上分隔符。最后,我们使用 getResponseCode() 方法获取响应代码来检查上传是否成功。

Java 文件上传示例:使用 HttpURLConnection 实现文件上传

原文地址: https://www.cveoy.top/t/topic/nOqM 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录