文件上传

接收文件

接受文件在 Controller 的方法中添加 UploadFile 类型的参数,在发送 http 请求时,请求的 key 是 UploadFile 类型的参数名.通常是 file,下面的案例是 uploadFile

import org.tio.utils.hutool.FileUtil;

  @RequestPath(value = "")
  public HttpResponse index(UploadFile uploadFile,HttpRequest request) throws Exception {
    if(uploadFile!=null) {
      byte[] fileData = uploadFile.getData();
      File file = new File(uploadFile.getName());
      FileUtil.writeBytes(fileData, file);
    }
    return Resps.json(request, "success");

  }

这段代码定义了一个处理 HTTP 请求的方法 index。该方法通过 @RequestPath 注解映射到一个空的 URL 路径(即默认路径)。它接收两个参数:一个 UploadFile 对象 uploadFile 和一个 HttpRequest 对象 request

  • 方法首先检查 uploadFile 是否为非空,如果非空,表示有文件上传。
  • 然后,从 uploadFile 对象中获取文件数据(字节数组)和文件名。
  • 使用 FileUtil.writeBytes 方法,将文件数据写入到一个新创建的 File 对象中,该对象使用上传文件的名称。
  • 最后,该方法返回一个 JSON 格式的响应,内容为字符串 "success"。

这个方法的主要功能是处理文件上传的请求,将上传的文件保存在服务器上,并返回一个表示操作成功的响应。

6.3.2.接受文件和包含上传参数

InputType 是 form 中的一个参数,可以省略 InputType 是 from 中的一个参数,可以省略

  @RequestPath(value = "")
  public HttpResponse index(UploadFile uploadFile, String InputType, String outputType, HttpRequest request)
      throws Exception {
    if (uploadFile != null) {
      byte[] fileData = uploadFile.getData();
      File file = new File(uploadFile.getName());
      FileUtil.writeBytes(fileData, file);
    }
    return Resps.json(request, "success");
  }

这段代码定义了一个处理 HTTP 请求的方法 index,它处理带有文件上传的请求。该方法接收四个参数:UploadFile 对象 uploadFile,两个字符串 InputTypeoutputType,以及一个 HttpRequest 对象 request

  • 如果 uploadFile 不为空,方法读取上传文件的数据(字节),然后创建一个新的 File 对象,文件名与上传的文件名相同。
  • 使用 FileUtil.writeBytes 方法,将上传文件的数据写入到新创建的文件中。
  • 最后,方法返回一个 JSON 格式的响应,内容为字符串 "success"。

6.3.3.UploadFile 常用方法

org.tio.http.common.UploadFile 可能代表在 Web 应用程序上下文中的一个上传文件。下面是这些方法的简要说明:

  1. getName(): 这个方法返回上传文件的名称。它用于识别文件,可能基于文件名扩展名确定其类型。

  2. getSize(): 这个方法返回上传文件的大小,以字节为单位。它可以用来检查文件的大小,这对于验证目的(例如,确保文件不太大,应用程序能够处理)是必要的。

  3. getData(): 这个方法返回文件的实际数据,以字节数组的形式。它用于处理文件的内容,如将其保存到服务器上或执行任何特定于文件的操作。

返回文件

  @RequestPath(value = "/filetest")
  public HttpResponse filetest(HttpRequest request) throws Exception {
    HttpResponse ret = Resps.file(request, new File("d:/tio.exe"));
    return ret;
  }


  @RequestPath(value = "/test.zip")
  public HttpResponse test_zip(HttpRequest request) throws Exception {
    String root = request.httpConfig.getPageRoot(request);
    HttpResponse ret = Resps.file(request, new File(root, "test/test.zip"));
    return ret;
  }

这两个方法都涉及处理 HTTP 请求并返回文件作为响应。

  1. filetest 方法:

    • 通过 @RequestPath 注解映射到 /filetest URL 路径。
    • 方法使用 Resps.file 创建一个 HttpResponse 对象,该对象将发送位于 "d:/tio.exe" 的文件作为响应。
  2. test_zip 方法:

    • 映射到 /test.zip URL 路径。
    • 首先,使用 request.httpConfig.getPageRoot 获取服务器的根目录。
    • 然后,使用 Resps.file 创建 HttpResponse 对象,返回位于根目录下 "test/test.zip" 路径的文件。