idtitlesidebar_label
upload_download
上传下载
上传下载

Forest从 1.4.0 版本开始支持多种形式的文件上传和文件下载功能

上传

  1. /**
  2. * 用@DataFile注解修饰要上传的参数对象
  3. * OnProgress参数为监听上传进度的回调函数
  4. */
  5. @Post(url = "/upload")
  6. Map upload(@DataFile("file") String filePath, OnProgress onProgress);

调用上传接口以及监听上传进度的代码如下:

  1. Map result = myClient.upload("D:\\TestUpload\\xxx.jpg", progress -> {
  2. System.out.println("total bytes: " + progress.getTotalBytes()); // 文件大小
  3. System.out.println("current bytes: " + progress.getCurrentBytes()); // 已上传字节数
  4. System.out.println("progress: " + Math.round(progress.getRate() * 100) + "%"); // 已上传百分比
  5. if (progress.isDone()) { // 是否上传完成
  6. System.out.println("-------- Upload Completed! --------");
  7. }
  8. });

在文件上传的接口定义中,除了可以使用字符串表示文件路径外,还可以用以下几种类型的对象表示要上传的文件:

  1. /**
  2. * File类型对象
  3. */
  4. @Post(url = "/upload")
  5. Map upload(@DataFile("file") File file, OnProgress onProgress);
  6. /**
  7. * byte数组
  8. * 使用byte数组和Inputstream对象时一定要定义fileName属性
  9. */
  10. @Post(url = "/upload")
  11. Map upload(@DataFile(value = "file", fileName = "${1}") byte[] bytes, String filename);
  12. /**
  13. * Inputstream 对象
  14. * 使用byte数组和Inputstream对象时一定要定义fileName属性
  15. */
  16. @Post(url = "/upload")
  17. Map upload(@DataFile(value = "file", fileName = "${1}") InputStream in, String filename);
  18. /**
  19. * Spring Web MVC 中的 MultipartFile 对象
  20. */
  21. @PostRequest(url = "/upload")
  22. Map upload(@DataFile(value = "file") MultipartFile multipartFile, OnProgress onProgress);
  23. /**
  24. * Spring 的 Resource 对象
  25. */
  26. @Post(url = "/upload")
  27. Map upload(@DataFile(value = "file") Resource resource);

下载

  1. /**
  2. * 在方法上加上@DownloadFile注解
  3. * dir属性表示文件下载到哪个目录
  4. * filename属性表示文件下载成功后以什么名字保存,如果不填,这默认从URL中取得文件名
  5. * OnProgress参数为监听上传进度的回调函数
  6. */
  7. @Get(url = "http://localhost:8080/images/xxx.jpg")
  8. @DownloadFile(dir = "${0}", filename = "${1}")
  9. File downloadFile(String dir, String filename, OnProgress onProgress);

调用下载接口以及监听上传进度的代码如下:

  1. File file = myClient.downloadFile("D:\\TestDownload", progress -> {
  2. System.out.println("total bytes: " + progress.getTotalBytes()); // 文件大小
  3. System.out.println("current bytes: " + progress.getCurrentBytes()); // 已下载字节数
  4. System.out.println("progress: " + Math.round(progress.getRate() * 100) + "%"); // 已下载百分比
  5. if (progress.isDone()) { // 是否下载完成
  6. System.out.println("-------- Download Completed! --------");
  7. }
  8. });

如果您不想将文件下载到硬盘上,而是直接在内存中读取,可以去掉@DownloadFile注解,并且用以下几种方式定义接口:

  1. /**
  2. * 返回类型用byte[],可将下载的文件转换成字节数组
  3. */
  4. @GetRequest(url = "http://localhost:8080/images/test-img.jpg")
  5. byte[] downloadImageToByteArray();
  6. /**
  7. * 返回类型用InputStream,用流的方式读取文件内容
  8. */
  9. @GetRequest(url = "http://localhost:8080/images/test-img.jpg")
  10. InputStream downloadImageToInputStream();

:::caution 注意 用File类型定义的文件下载接口方法,一定要加上@DownloadFile注解 :::