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;
 }
}

猜你喜欢

转载自www.cnblogs.com/xiaowenwen/p/11455871.html