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

在Java中创建一个小型文件上传工具,可以通过使用内置的HttpURLConnection和java.net包来实现客户端与服务端之间的文件传输。下面是一个简单但实用的实现方式,适用于小项目或学习用途。
文件上传通常采用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";
}
}
}
为了完整演示,可以使用Spring Boot快速搭建一个接收上传的接口。
立即学习“Java免费学习笔记(深入)”;
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
Content-Type头为multipart/form-data
以上就是Java中如何创建一个小型文件上传工具的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号