Java 文件上传和下载可以使用Java中的URLConnection和HttpURLConnection类。以下是一个简单的Java文件上传和下载的示例代码:

文件上传:

import java.io.*;
import java.net.*;

public class FileUploader {
    public static void main(String[] args) throws Exception {
        String filepath = "C:/Users/username/Desktop/file.txt";
        String url = "http://localhost:8080/upload";

        File file = new File(filepath);
        URLConnection conn = new URL(url).openConnection();
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + "----WebKitFormBoundary7MA4YWxkTrZu0gW");
        OutputStream outputStream = conn.getOutputStream();

        PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream, "UTF-8"), true);

        writer.append("------WebKitFormBoundary7MA4YWxkTrZu0gW\r\n")
                .append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"\r\n")
                .append("Content-Type: " + URLConnection.guessContentTypeFromName(file.getName()) + "\r\n\r\n")
                .flush();

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

        writer.append("\r\n").flush();
        writer.append("------WebKitFormBoundary7MA4YWxkTrZu0gW--\r\n").flush();

        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line = null;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
    }
}

文件下载:

import java.io.*;
import java.net.*;

public class FileDownloader {
    public static void main(String[] args) throws Exception {
        String fileUrl = "http://localhost:8080/download/file.txt";
        String saveDir = "C:/Users/username/Desktop/";

        URL url = new URL(fileUrl);
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
        int responseCode = httpConn.getResponseCode();

        if (responseCode == HttpURLConnection.HTTP_OK) {
            String fileName = "";
            String disposition = httpConn.getHeaderField("Content-Disposition");
            String contentType = httpConn.getContentType();
            int contentLength = httpConn.getContentLength();

            if (disposition != null) {
                int index = disposition.indexOf("filename=");
                if (index > 0) {
                    fileName = disposition.substring(index + 10, disposition.length() - 1);
                }
            } else {
                fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1, fileUrl.length());
            }

            InputStream inputStream = httpConn.getInputStream();
            String saveFilePath = saveDir + fileName;

            FileOutputStream outputStream = new FileOutputStream(saveFilePath);

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

            outputStream.close();
            inputStream.close();
            System.out.println("File downloaded");
        } else {
            System.out.println("Server returned response code: " + responseCode);
        }
        httpConn.disconnect();
    }
}
java文件上传下载

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

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