登录
首页 >  文章 >  java教程

Java实现简单文件上传教程

时间:2026-01-13 17:13:47 175浏览 收藏

在文章实战开发的过程中,我们经常会遇到一些这样那样的问题,然后要卡好半天,等问题解决了才发现原来一些细节知识点还是没有掌握好。今天golang学习网就整理分享《Java实现简易文件上传工具教程》,聊聊,希望可以帮助到正在努力赚钱的你。

答案:Java可通过HttpURLConnection实现文件上传,客户端使用multipart/form-data格式发送文件,服务端用Spring Boot接收并保存。需注意boundary唯一性、内容类型设置、大文件分块读写及安全校验,适用于小项目或学习场景。

Java中如何创建一个小型文件上传工具

在Java中创建一个小型文件上传工具,可以通过使用内置的HttpURLConnectionjava.net包来实现客户端与服务端之间的文件传输。下面是一个简单但实用的实现方式,适用于小项目或学习用途。

1. 使用HTTP协议实现文件上传

文件上传通常采用HTTP的POST请求,以multipart/form-data格式发送数据。Java原生支持这种格式,无需引入第三方库。

客户端代码示例:

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class FileUploader {
    public static void upload(String filePath, String uploadUrl) throws Exception {
        File file = new File(filePath);
        URL url = new URL(uploadUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        
        // 设置请求方式和头信息
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

        String boundary = "----WebKitFormBoundary7MA4YWxkTrZu0gW";

        try (DataOutputStream out = new DataOutputStream(connection.getOutputStream());
             FileInputStream fileInputStream = new FileInputStream(file)) {

            // 写入表单字段(文件部分)
            out.writeBytes("--" + boundary + "\r\n");
            out.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"\r\n");
            out.writeBytes("Content-Type: " + getContentType(file.getName()) + "\r\n\r\n");

            // 读取文件内容并写入输出流
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
            out.writeBytes("\r\n");
            out.writeBytes("--" + boundary + "--\r\n");

            out.flush();
        }

        // 检查响应状态
        int responseCode = connection.getResponseCode();
        if (responseCode == 200) {
            System.out.println("文件上传成功");
        } else {
            System.out.println("上传失败,响应码:" + responseCode);
        }
    }

    private static String getContentType(String fileName) {
        if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")) {
            return "image/jpeg";
        } else if (fileName.endsWith(".png")) {
            return "image/png";
        } else if (fileName.endsWith(".pdf")) {
            return "application/pdf";
        } else {
            return "application/octet-stream";
        }
    }
}

2. 简易服务端接收文件(使用Spring Boot)

为了完整演示,可以使用Spring Boot快速搭建一个接收上传的接口。

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileOutputStream;
import java.io.InputStream;

@RestController
public class UploadController {

    @PostMapping("/upload")
    public String handleFileUpload(@RequestParam("file") MultipartFile file) {
        try (InputStream in = file.getInputStream()) {
            FileOutputStream fos = new FileOutputStream("uploaded_" + file.getOriginalFilename());
            byte[] buffer = new byte[4096];
            int len;
            while ((len = in.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }
            fos.close();
            return "文件保存成功: " + file.getOriginalFilename();
        } catch (Exception e) {
            return "上传失败: " + e.getMessage();
        }
    }
}

确保Spring Boot项目中已启用Multipart配置(默认开启),并限制文件大小(可在application.properties中设置):

spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB

3. 使用注意点

  • boundary字符串必须唯一,避免与文件内容冲突
  • 正确设置Content-Type头为multipart/form-data
  • 文件较大时建议分块读写,避免内存溢出
  • 生产环境推荐使用Apache HttpClient或OkHttp等成熟库提升稳定性
  • 服务端需做文件类型、大小、路径安全校验
基本上就这些。用Java标准库就能实现基础文件上传功能,适合轻量级需求。

终于介绍完啦!小伙伴们,这篇关于《Java实现简单文件上传教程》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布文章相关知识,快来关注吧!

前往漫画官网入口并下载 ➜
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>