文件上传
接收文件
接受文件在 Controller 的方法中添加 UploadFile 类型的参数,在发送 http 请求时,请求的 key 是 UploadFile 类型的参数名.通常是 file,下面的案例是 uploadFile
package com.litongjava.tio.web.hello.controller;
import java.io.File;
import com.litongjava.annotation.RequestPath;
import com.litongjava.tio.boot.http.TioRequestContext;
import com.litongjava.tio.http.common.HttpResponse;
import com.litongjava.tio.http.common.UploadFile;
import com.litongjava.tio.utils.hutool.FileUtil;
@RequestPath(value = "/simple/upload")
public class SimleUploadController {
@RequestPath(value = "")
public HttpResponse index(UploadFile uploadFile){
if (uploadFile != null) {
byte[] fileData = uploadFile.getData();
File file = new File(uploadFile.getName());
FileUtil.writeBytes(fileData, file);
}
HttpResponse response = TioRequestContext.getResponse();
return response.setString("sucess");
}
}
这段代码定义了一个处理 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,两个字符串 InputType 和 outputType,以及一个 HttpRequest 对象 request。
- 如果
uploadFile不为空,方法读取上传文件的数据(字节),然后创建一个新的File对象,文件名与上传的文件名相同。 - 使用
FileUtil.writeBytes方法,将上传文件的数据写入到新创建的文件中。 - 最后,方法返回一个 JSON 格式的响应,内容为字符串 "success"。
6.3.3.UploadFile 常用方法
类 org.tio.http.common.UploadFile 可能代表在 Web 应用程序上下文中的一个上传文件。下面是这些方法的简要说明:
getName(): 这个方法返回上传文件的名称。它用于识别文件,可能基于文件名扩展名确定其类型。getSize(): 这个方法返回上传文件的大小,以字节为单位。它可以用来检查文件的大小,这对于验证目的(例如,确保文件不太大,应用程序能够处理)是必要的。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 请求并返回文件作为响应。
filetest方法:- 通过
@RequestPath注解映射到/filetestURL 路径。 - 方法使用
Resps.file创建一个HttpResponse对象,该对象将发送位于 "d:/tio.exe" 的文件作为响应。
- 通过
test_zip方法:- 映射到
/test.zipURL 路径。 - 首先,使用
request.httpConfig.getPageRoot获取服务器的根目录。 - 然后,使用
Resps.file创建HttpResponse对象,返回位于根目录下 "test/test.zip" 路径的文件。
- 映射到
