实现一个简单的文件上传服务,不依赖任何第三方库,方便在只有JDK的环境中使用,参考代码如下:
package com.test;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.Executors;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
public class FileHttpServer {
private String workDir = "/tmp";
private int port = 19000;
public static void main(String[] args) throws IOException {
new FileHttpServer(args);
}
public FileHttpServer(String[] args) throws IOException {
if (args.length >= 1) {
port = Integer.parseInt(args[0]);
}
if (args.length >= 2) {
workDir = args[1];
}
HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
server.setExecutor(Executors.newCachedThreadPool());
server.createContext("/upload", new FileUploadHttpHandler());
server.createContext("/download", new FileDownLoadHttpHandler());
server.start();
System.out.println("FileHttpServer started. port=" + port + ", workDir=" + workDir);
}
class FileUploadHttpHandler implements HttpHandler {
@Override
public void handle(HttpExchange arg0) throws IOException {
System.out.println("remoteAddress=" + arg0.getRemoteAddress().getAddress().getHostName());
String fileName = arg0.getRequestHeaders().getFirst("fileName");
if (fileName == null || "".equals(fileName)) {
fileName = "" + System.currentTimeMillis();
}
BufferedInputStream input = new BufferedInputStream(arg0.getRequestBody());
byte[] b = new byte[1024];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while ((len = input.read(b)) != -1) {
bos.write(b, 0, len);
}
byte[] recvFile = bos.toByteArray();
System.out.println("receive file. fileName=" + fileName + ", fileLength=" + recvFile.length);
Path savePath = Paths.get(workDir, fileName);
System.out.println("write file. savePath=" + savePath.toString());
Files.write(savePath, recvFile);
String result = "ok";
arg0.sendResponseHeaders(200, result.getBytes().length);
arg0.getResponseBody().write(result.getBytes());
arg0.getResponseBody().close();
}
}
class FileDownLoadHttpHandler implements HttpHandler {
@Override
public void handle(HttpExchange arg0) throws IOException {
System.out.println("remoteAddress=" + arg0.getRemoteAddress().getAddress().getHostName());
String fileName = arg0.getRequestHeaders().getFirst("fileName");
if (fileName == null || "".equals(fileName)) {
arg0.sendResponseHeaders(404, 0);
return;
}
byte[] result = Files.readAllBytes(Paths.get(workDir, fileName));
System.out.println("fileName=" + fileName + ", len=" + result.length);
arg0.getResponseHeaders().add("Content-Type", "application/octet-stream");
arg0.getResponseHeaders().add("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
arg0.sendResponseHeaders(200, result.length);
arg0.getResponseBody().write(result);
arg0.getResponseBody().close();
}
}
}
可使用curl上传
curl http://127.0.0.1:19000/upload -T D:/Temp/eclipse_class.log -H 'fileName: eclipse_class.log' -v
执行结果:
* Trying 127.0.0.1:19000...
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0* Connected to 127.0.0.1 (127.0.0.1) port 19000 (#0)
> PUT /upload HTTP/1.1
> Host: 127.0.0.1:19000
> User-Agent: curl/7.75.0
> Accept: */*
> fileName: eclipse_class.log
> Content-Length: 1048210
> Expect: 100-continue
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 100 Continue
< Content-Length: 0
} [65536 bytes data]
* We are completely uploaded and fine
* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< Date: Thu, 30 Jun 2022 12:33:03 GMT
< Content-length: 2
<
{ [2 bytes data]
100 1023k 100 2 100 1023k 76 38.4M --:--:-- --:--:-- --:--:-- 39.9Mok
* Connection #0 to host 127.0.0.1 left intact