Struts2 文件上传

举报
小傅哥 发表于 2021/04/23 02:05:36 2021/04/23
4.9k+ 0 0
【摘要】 单文件上传 第一步:在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...

单文件上传


      第一步:在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/form-data" action="${pageContext.request.contextPath}/xxx.action" method="post">
        <input  type="file" name="uploadImage">
      </form>
      第三步:在Action类中添加以下属性,属性红色部分对应于表单中文件字段的名称:
      public class HelloWorldAction{
       private File uploadImage;//得到上传的文件
       private String uploadImageContentType;//得到文件的类型
       private String uploadImageFileName;//得到文件的名称
       //这里略省了属性的getter/setter方法
       public String upload() throws Exception{
      	String realpath = ServletActionContext.getServletContext().getRealPath("/images");
      	File file = new File(realpath);
     	if(!file.exists()) file.mkdirs();
      	FileUtils.copyFile(uploadImage, new File(file, uploadImageFileName));
     	return "success";
        }
      }
  
 


多文件上传


      第一步:在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/form-data" action="${pageContext.request.contextPath}/xxx.action" method="post">
        <input  type="file" name="uploadImages">
        <input  type="file" name="uploadImages">
      </form>
      第三步:在Action类中添加以下属性,属性红色部分对应于表单中文件字段的名称:
      public class HelloWorldAction{
       private File[] uploadImages;//得到上传的文件
       private String[] uploadImagesContentType;//得到文件的类型
       private String[] uploadImagesFileName;//得到文件的名称
       //这里略省了属性的getter/setter方法
       public String upload() throws Exception{
      	String realpath = ServletActionContext.getServletContext().getRealPath("/images");
      	File file = new File(realpath);
     	if(!file.exists()) file.mkdirs();
     	for(int i=0 ;i<uploadImages.length; i++){ File uploadImage = uploadImages[i];
       FileUtils.copyFile(uploadImage, new File(file, uploadImagesFileName[i]));
      }
     	return "success";
        }}
  
 


 

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

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

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

作者其他文章

评论(0

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

    全部回复

    上滑加载中

    设置昵称

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

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

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