在 Java 中通过 HTTP 上传文件,常见做法有几种,取决于你使用的是客户端还是服务端,以及使用的技术栈。下面按常见场景说明。
import java.net.http.*;
import java.net.URI;
import java.nio.file.Path;
import java.time.Duration;
public class FileUpload {
public static void main(String[] args) throws Exception {
var file = Path.of("test.txt");
var request = HttpRequest.newBuilder()
.uri(URI.create("http://localhost:8080/upload"))
.timeout(Duration.ofMinutes(1))
.header("Content-Type", "multipart/form-data")
.POST(HttpRequest.BodyPublishers.ofFile(file))
.build();
var client = HttpClient.newHttpClient();
HttpResponse<String> response =
client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode());
System.out.println(response.body());
}
}
⚠️ 注意:
原生 HttpClient 不直接支持 multipart/form-data 封装,如需表单上传,需要自己构造 body(较复杂),或使用下面方式。
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.14</version>
</dependency>
import org.apache.http.*;
import org.apache.http.client.methods.*;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import java.io.File;
public class UploadClient {
public static void main(String[] args) throws Exception {
CloseableHttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost("http://localhost:8080/upload");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addBinaryBody(
"file",
new File("test.txt"),
ContentType.APPLICATION_OCTET_STREAM,
"test.txt"
);
post.setEntity(builder.build());
CloseableHttpResponse response = client.execute(post);
System.out.println(response.getStatusLine());
client.close();
}
}
OkHttpClient client = new OkHttpClient();
RequestBody body = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", "test.txt",
RequestBody.create(new File("test.txt"),
MediaType.parse("text/plain")))
.build();
Request request = new Request.Builder()
.url("http://localhost:8080/upload")
.post(body)
.build();
client.newCall(request).execute();
@RestController
public class UploadController {
@PostMapping("/upload")
public String upload(@RequestParam("file") MultipartFile file) throws Exception {
file.transferTo(new File("upload/" + file.getOriginalFilename()));
return "上传成功";
}
}
spring:
servlet:
multipart:
max-file-size: 10MB
max-request-size: 10MB
@WebServlet("/upload")
@MultipartConfig
public class UploadServlet extends HttpServlet {
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
Part part = req.getPart("file");
part.write("upload/" + part.getSubmittedFileName());
}
}
| 类型 | 说明 |
|---|---|
| multipart/form-data | 文件上传标准 |
| application/octet-stream | 纯文件流 |
| application/json | 不适合直接传文件 |
✅ 客户端
✅ 服务端
如果你有具体场景(如:Spring Boot 上传、大文件、断点续传、前后端分离),可以告诉我,我给你更针对性的代码。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。