【Jsp精品源码栏目提醒】:以下是网学会员为您推荐的Jsp精品源码-在Struts2中上传图片文件 - 其它资料,希望本篇文章对您学习有所帮助。
在 Struts2 中上传图片文件 泸州职业技术学院信息工程系 华卫一、操作步骤1、创建一个 Web 项目:UploadFile 将2、 Struts 框架所需的 jar 包拷贝到 WebRootWEB-INFlib 目录下, 单击 , 【Libraries】 然后设置 UploadFile 项目的属性, 【Java Build Path】选择选项卡,单击【Add JARs...】,添加 WebRootWEB-INFlib 里的全部 jar 包。
3、在 src 里创建包:cn.hw.struts24、修改 web.xml 文件5、在 src 里创建 struts.xml 配置文件6、在 WebRoot 里创建 uploadFile.
jsp 和 uploadOK.
jsp7、项目的目录结构如下图所示:二、源代码文件1、web.xml struts2 org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter struts2 .action2、struts.xml /uploadOK.
jsp3、uploadFile.
jsp上传图片文件4、uploadOK.
jsp 文件上传成功!更名为【uploadFileName】!5、UploadFileActionpackage cn.hw.struts2import java.io.Fileimport javax.servlet.http.HttpServletResponseimport org.apache.commons.io.FileUtilsimport org.apache.struts2.ServletActionContextimport com.opensymphony.xwork2.ActionSupportimport com.sun.jmx.snmp.Timestamppublic class UploadFileAction extends ActionSupport private File uploadFile// 得到上传的文件 private String uploadFileContentType// 得到文件的类型 private String uploadFileName// 得到文件的名称 public File getUploadFile return uploadFile public void setUploadFileFile uploadFile this.uploadFile uploadFile public String getUploadFileContentType return uploadFileContentType public void setUploadFileContentTypeString uploadFileContentType this.uploadFileContentType uploadFileContentType public String getUploadFileName return uploadFileName public void setUploadFileNameString uploadFileName this.uploadFileName uploadFileName //上传文件 public String upload throws Exception String realpath ServletActionContext.getServletContext.getRealPath /images File dir new Filerealpath if dir.exists dir.mkdir ifuploadFileContentType.equalsimage/jpeg uploadFileContentType.jpg else if uploadFileContentType.equalsimage/png uploadFileContentType.png else ifuploadFileContentType.equalsimage/gif uploadFileContentType.gif uploadFileNameimagenew Timestamp.getDateTimeuploadFileContentType FileUtils.copyFileuploadFilenew Filedir uploadFileName return SUCCESS 三、运行结果1、部署项目2、启动 Tomcat 服务器3、在浏览器里地址栏里输入 http://localhost:8080/TestStruts2/uploadFile.
jsp,敲回车;4、不单击【浏览】按钮,直接单击【上传】按钮,会弹出消息框:5、单击【浏览】按钮,弹出【文件上载】对话框;6、选择一张图片,比如选择【沙漠.jpg】文件;7、单击【上传】按钮,文件提交到服务器,并在 uploadOK.
jsp 页面显示该图片;