Struts2 文件上传

举报
小傅哥 发表于 2021/04/23 02:05:36 2021/04/23
【摘要】 单文件上传 第一步:在WEB-INF/lib下加入commons-fileupload-1.2.1.jar、commons-io-1.3.2.jar。这两个文件可以从http://commons.apache.org/下载。第二步:把form表的enctype设置为:“multipart/form-data“,如下:<form enctype="multipart/f...

单文件上传


  
  1. 第一步:在WEB-INF/lib下加入commons-fileupload-1.2.1.jar、commons-io-1.3.2.jar。这两个文件可以从http://commons.apache.org/下载。
  2. 第二步:把form表的enctype设置为:“multipart/form-data“,如下:
  3. <form enctype="multipart/form-data" action="${pageContext.request.contextPath}/xxx.action" method="post">
  4. <input type="file" name="uploadImage">
  5. </form>
  6. 第三步:在Action类中添加以下属性,属性红色部分对应于表单中文件字段的名称:
  7. public class HelloWorldAction{
  8. private File uploadImage;//得到上传的文件
  9. private String uploadImageContentType;//得到文件的类型
  10. private String uploadImageFileName;//得到文件的名称
  11. //这里略省了属性的getter/setter方法
  12. public String upload() throws Exception{
  13. String realpath = ServletActionContext.getServletContext().getRealPath("/images");
  14. File file = new File(realpath);
  15. if(!file.exists()) file.mkdirs();
  16. FileUtils.copyFile(uploadImage, new File(file, uploadImageFileName));
  17. return "success";
  18. }
  19. }


多文件上传


  
  1. 第一步:在WEB-INF/lib下加入commons-fileupload-1.2.1.jar、commons-io-1.3.2.jar。这两个文件可以从http://commons.apache.org/下载。
  2. 第二步:把form表的enctype设置为:“multipart/form-data“,如下:
  3. <form enctype="multipart/form-data" action="${pageContext.request.contextPath}/xxx.action" method="post">
  4. <input type="file" name="uploadImages">
  5. <input type="file" name="uploadImages">
  6. </form>
  7. 第三步:在Action类中添加以下属性,属性红色部分对应于表单中文件字段的名称:
  8. public class HelloWorldAction{
  9. private File[] uploadImages;//得到上传的文件
  10. private String[] uploadImagesContentType;//得到文件的类型
  11. private String[] uploadImagesFileName;//得到文件的名称
  12. //这里略省了属性的getter/setter方法
  13. public String upload() throws Exception{
  14. String realpath = ServletActionContext.getServletContext().getRealPath("/images");
  15. File file = new File(realpath);
  16. if(!file.exists()) file.mkdirs();
  17. for(int i=0 ;i<uploadImages.length; i++){ File uploadImage = uploadImages[i];
  18. FileUtils.copyFile(uploadImage, new File(file, uploadImagesFileName[i]));
  19. }
  20. return "success";
  21. }}


 

文章来源: bugstack.blog.csdn.net,作者:Yao__Shun__Yu,版权归原作者所有,如需转载,请联系作者。

原文链接:bugstack.blog.csdn.net/article/details/7988135

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。