Struts中的文件上传
Posted xiaowenwen
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Struts中的文件上传相关的知识,希望对你有一定的参考价值。
Struts中的表单
<s:form action="/upload" enctype="multipart/form-data">
<s:textfield label="用户名" name="username"/>
<s:textfield label="密码" name="password"/>
<s:file label="照片" name="photo"/>
<s:submit value="上传"/>
</s:form>
注意:使用struts中的标签需要导入<%@ taglib prefix="s" uri="/struts-tags" %>
动作类
package com.lzw.web.action;
import java.io.File;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class UploadAction extends ActionSupport
private String username;
private String password;
private File photo;
private String photoContentType;//文件类型
private String photoFileName;//文件名称
public String upload()
System.out.println(username);
System.out.println(password);
System.out.println(photoContentType);
System.out.println(photoFileName);
System.out.println(photo);
//1设置文件保存目录
String dir = ServletActionContext.getServletContext().getRealPath("/WEB-INF/upload") + "/" + username;
//创建文件路径
File f = new File(dir);
if(f.exists() == false)
f.mkdirs();
String fileSavePath = dir + "/" + photoFileName;
photo.renameTo(new File(fileSavePath));//保存文件
return NONE;
public void setUsername(String username)
this.username = username;
public void setPassword(String password)
this.password = password;
public void setPhoto(File photo)
this.photo = photo;
public void setPhotoContentType(String photoContentType)
this.photoContentType = photoContentType;
public void setPhotoFileName(String photoFileName)
this.photoFileName = photoFileName;
以上是关于Struts中的文件上传的主要内容,如果未能解决你的问题,请参考以下文章