Java:一个简单的文件上传下载服务器

实现一个简单的文件上传服务,不依赖任何第三方库,方便在只有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

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值