• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Struts2实现文件上传功能实例解析

java 搞代码 4年前 (2022-01-05) 20次浏览 已收录 0个评论

这篇文章主要介绍了Struts2实现文件上传功能实例解析,非常不错,具有参考借鉴价值,需要的朋友可以参考下

一、 搭建struts2环境

在myeclipse下,右击项目->MyEclipse->Project Facets->install Apache Struts2。

如要自己搭建,需下载struts2包,写struts.xml配置文件。

web.xml文件配置如下:

  struts2org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter struts2*.action

二、 文件上传

1.前台页面:

上传页面:

   <br> ${result} 

input name属性与后台命名一致。

上传失败页面:

  <h2>上传失败</h2><s></s>

需:

 

2.后台Action

主要属性upload,uploadContentType,uploadFileName。

 package com.yf.action; import java.io.File; import org.apache.commons.io.FileUtils; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; public class UploadAction extends ActionSupport{ private File upload; private String uploadContentType; private String uploadFileName; private String result; public File getUoload() { return upload; } public void setUpload(File upload) { this.upload = upload; } public String getUploadContentType() { return uploadContentType; } public void setUploadContentType(String uploadContentType) { this.uploadContentType = uploadContentType; } public String getUploadFileName() { return uploadFileName; } public void setUploadFileName(String uploadFileName) { this.uploadFileName = uploadFileName; } public <a style="color:transparent">来源gao*daima.com搞@代#码网</a>String getResult() { return result; } public void setResult(String result) { this.result = result; } @Override public String execute() throws Exception { String path = ServletActionContext.getServletContext().getRealPath("/images"); File file = new File(path); if(!file.exists()){ file.mkdir(); } System.out.println(upload); FileUtils.copyFile(upload, new File(file,uploadFileName)); result = "上传成功"; return SUCCESS; } }

3.struts.xml文件配置

配置action及配置拦截器限制上传文件的类型及大小。

     /index.jsp/error.jsp<!-- 配置拦截器限制上传文件的类型及大小 --> image/bmp,image/x-png,image/gif,image/jpeg2M

4.新建properties文件

文件上传失败信息显示到前台,处理显示出错信息。

文件内容如下:

 struts.messages.error.file.too/large=\u4E0A\u4F20\u6587\u4EF6\u592A\u5927\u4E86\uFF01 struts.messages.error.content.type.not.allowed=\u4E0A\u4F20\u6587\u4EF6\u7C7B\u578B\u4E0D\u7B26\uFF01

即添加:

Name:struts.messages.error.file.too/large

value : 上传文件太大了!

Name : struts.messages.error.content.type.not.allowed

value: 上传文件类型不符!

运行结果如下:

选择jpg图片,大小不超过2M,运行后

选择非图片文件:

如需批量上传文件,将后台upload,uploadContentType,uploadFileName均改为List,循环读取上传文件保存到硬盘,前台加入input ,name属性一致。

以上所述是小编给大家介绍的Struts2实现文件上传功能实例解析,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!

以上就是Struts2实现文件上传功能实例解析的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Struts2实现文件上传功能实例解析

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址