Struts2实现文件上传
来源:互联网 发布:淘宝客服术语模板 编辑:程序博客网 时间:2024/04/29 11:56
今天来和大家分享一下使用struts2进行文件上传的小技巧。首先我们要知道的是,上传文件必须是以二进制数据的形式发送给服务器,因此,必须将提交表单的method设置为post,将enctype设置为multipart/form-data。
struts2默认使用的是Jakarta的Common-FileUpload上传框架,因此还需要导入两个jar文件:commons-io-2.2.jar和commons-fileupload-1.3.1.jar
接下来给大家找是一个小例子。
首先是文件上传页面uploadFile.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib uri="/struts-tags" prefix="s"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> </head> <body> <form action="UploadAction.action" enctype="multipart/form-data" method="post"> 上传 <s:file name="upload" /> </form> </body></html>接下来是处理请求的action
public class UploadAction extends ActionSupport{private File upload;//上传文件域private String uploadContentType;//上传文件类型private String uploadFileName;//上传文件属性//上传文件在保存位置,在struts.xml中配置private String savePath;public File getUpload() {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 void setSavePath(String value){this.savePath = value;}//获取上传文件保存位置public String getSavePath() throws Exception{return ServletActionContext.getServletContext().getRealPath(savePath);}public String execute() throws Exception{String path = getSavePath()+"\\"+getUploadFileName();//上传文件保存路径FileOutputStream fos = new FileOutputStream(path);FileInputStream fis = new FileInputStream(getUpload());byte[] buffer = new byte[1024];int len = 0;while((len = fis.read(buffer))>0)fos.write(buffer, 0, len);return SUCCESS;}}
在本例中,我将在服务器端保存的文件名与上传的文件名设为了一样的,在实际应用中,可以使用UUID生成唯一的文件名。
在struts.xml中配置文件保存路径参数savePath:
<package name="upload" extends="struts-default"><action name="UploadAction" class="action.UploadAction"><param name="savePath">/uploadFiles</param><result>/suc.jsp</result></action></package>
另外,在工程目录下WebRoot下最好建一个文件夹,命名为struts.xml中savePath配置的参数值,例如我将savePath参数设为/uploadFiles,则建一个uploadFiles文件夹,这样就不用在服务器目录下手动建立uploadFiles文件夹了。
好了,现在我们来看一下效果:
首先登陆index.jsp:
然后选择一个文件,点击提交后会跳转到成功界面,
然后在服务器部署目录下查看保存的文件即可。是不是很简单呢!
0 0
- Struts2实现文件上传
- struts2实现文件上传
- struts2实现文件上传
- Struts2实现文件上传
- struts2实现文件上传
- struts2实现文件上传
- struts2实现文件上传
- struts2实现文件上传
- struts2实现文件上传
- Struts2实现文件上传
- Struts2实现文件上传
- Struts2实现文件上传
- Struts2实现文件上传
- struts2实现上传文件
- Struts2实现文件上传
- Struts2实现文件上传
- Struts2实现文件上传
- Struts2实现文件上传
- Invalidate()
- sleep(0)
- 1033. 旧键盘打字(20)
- oralce 一个SQL插入多条记录
- hdu1693 Eat the Trees 插头DP
- Struts2实现文件上传
- 单例模式
- spring+mybatis+restful的搭建
- 程序员高效技巧系列 -- 完全脱离鼠标的终端
- LintCode-交错正负数
- css 类选择器 id选择器 html选择器 通配符选择器 父子选择器
- hdu 5229 ZCC loves strings
- 网银支付接口资料小总
- Git常用命令