ActFramework中实现文件上传

文件上传是一种常见的web应用功能。这篇小灶讲述如何在ActFramework中实现文件上传,包括单文件上传和多文件上传两种情况。

首先我们定义一个Model类Document用于演示单文件上传的情况:

  1. public class Document implements SimpleBean {
  2. public String desc;
  3. public String subject;
  4. public File attachment;
  5. public Document(String subject, String desc, File attachment) {
  6. this.desc = desc;
  7. this.subject = subject;
  8. this.attachment = attachment;
  9. }
  10. }

下面是处理单文件上传的请求响应函数:

  1. @PostAction("/single")
  2. public Document handleSingleFile(File file, String subject, String desc) {
  3. return new Document(subject, desc, file);
  4. }

对应单文件上传的HTML Form:

  1. <form action="/single" method="post" enctype="multipart/form-data">
  2. <div>
  3. <input name="subject" placeholder="subject">
  4. </div>
  5. <div>
  6. <input name="desc" placeholder="description">
  7. </div>
  8. <div>
  9. <input name="file" type="file" placeholder="file">
  10. </div>
  11. <div>
  12. <button type="submit">Submit</button>
  13. </div>
  14. </form>

以上就是Act应用中处理单文件上传的一种方式。下面来看看多文件上传的处理方式。

先定义一个Model类用于演示多文件上传:

  1. public class Archive implements SimpleBean {
  2. public String desc;
  3. public String subject;
  4. public File[] attachments;
  5. public Archive(String subject, String desc, File[] attachments) {
  6. this.desc = desc;
  7. this.subject = subject;
  8. this.attachments = attachments;
  9. }
  10. }

处理多文件上传的请求响应函数:

  1. @PostAction("/multi")
  2. // Note the param type `File[]` can be changed to `List<File>`
  3. public Archive handleMultipleFiles(File[] files, String subject, String desc) {
  4. return new Archive(subject, desc, files);
  5. }

对应的多文件上传的HTML Form:

  1. <form action="/multi" method="post" enctype="multipart/form-data">
  2. <div>
  3. <input name="subject" placeholder="subject">
  4. </div>
  5. <div>
  6. <input name="desc" placeholder="description">
  7. </div>
  8. <div>
  9. <input name="files" type="file" placeholder="file">
  10. </div>
  11. <div>
  12. <input name="files" type="file" placeholder="file">
  13. </div>
  14. <div>
  15. <input name="files" type="file" placeholder="file">
  16. </div>
  17. <div>
  18. <button type="submit">Submit</button>
  19. </div>
  20. </form>

这就是多文件上传的方式。

完整的源代码保存在码云