1.文件的上传:
1). 表单需要注意3点
2). Struts2 的文件上传实际上使用的是 Commons FileUpload 组件,所以需要导入对应的两个jar包,
commons-fileupload-1.3.jar;
commons-io-2.0.1.jar
3). Struts2 进行文件上传需要使用 FileUpload 拦截器
4). 基本的文件上传: 直接在 Action 中定义如下三个属性,并提供对应的getter,setter
//文件对应的File对象
private File [fileFieldName];
//文件类型
private String [fileFieldName]ContentType;
//文件名
private String [fileFieldName]FileName;
5). 使用 IO 流进行文件的上传即可.
在项目上建立 files 文件夹
eg.
uploadAction.java
public String upload(){
ServletContext servletContext = ServletActionContext.getServletContext();
//更改上传图片名称,防止重复,防止中文
SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmssS");//格式化时间输出
String Rname=sdf.format(new Date());//取得当前时间,Date()是java.util包里的,这作为真实名称
String name=imgFileName;//得到上传文件的原名称
int i=name.lastIndexOf(".");//原名称里倒数第一个"."在哪里
String ext=name.substring(i+1);//取得后缀,及"."后面的字符
carteImg = Rname+"."+ext;//拼凑而成
//文件上传的路径
String dir = servletContext.getRealPath("/files/" + imgFileName);
System.out.println(dir);
//输入输出流
FileOutputStream out = new FileOutputStream(dir);
FileInputStream in = new FileInputStream(img);
byte [] buffer = new byte[1024];
int len = 0;
//写入
while((len = in.read(buffer)) != -1){
out.write(buffer, 0, len);
}
out.close();
in.close();
return SUCCESS;
}
struts.xml
<action name="upload" extends="struts-default" method="upload">
<result name="success">/success.jsp</result>
</action>
show.jsp
<img src="<s:property value="'files/' + carteImg"/>">
1). 表单需要注意3点
2). Struts2 的文件上传实际上使用的是 Commons FileUpload 组件,所以需要导入对应的两个jar包,
commons-fileupload-1.3.jar;
commons-io-2.0.1.jar
3). Struts2 进行文件上传需要使用 FileUpload 拦截器
4). 基本的文件上传: 直接在 Action 中定义如下三个属性,并提供对应的getter,setter
//文件对应的File对象
private File [fileFieldName];
//文件类型
private String [fileFieldName]ContentType;
//文件名
private String [fileFieldName]FileName;
5). 使用 IO 流进行文件的上传即可.
在项目上建立 files 文件夹
eg.
uploadAction.java
public String upload(){
ServletContext servletContext = ServletActionContext.getServletContext();
//更改上传图片名称,防止重复,防止中文
SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmssS");//格式化时间输出
String Rname=sdf.format(new Date());//取得当前时间,Date()是java.util包里的,这作为真实名称
String name=imgFileName;//得到上传文件的原名称
int i=name.lastIndexOf(".");//原名称里倒数第一个"."在哪里
String ext=name.substring(i+1);//取得后缀,及"."后面的字符
carteImg = Rname+"."+ext;//拼凑而成
//文件上传的路径
String dir = servletContext.getRealPath("/files/" + imgFileName);
System.out.println(dir);
//输入输出流
FileOutputStream out = new FileOutputStream(dir);
FileInputStream in = new FileInputStream(img);
byte [] buffer = new byte[1024];
int len = 0;
//写入
while((len = in.read(buffer)) != -1){
out.write(buffer, 0, len);
}
out.close();
in.close();
return SUCCESS;
}
struts.xml
<action name="upload" extends="struts-default" method="upload">
<result name="success">/success.jsp</result>
</action>
show.jsp
<img src="<s:property value="'files/' + carteImg"/>">