struts2 上传文件


首先建立JSP页面  注意一定要有 enctype="multipart/form-data

  <form name="f1" id="f1" action="upload.action" method="post"  enctype="multipart/form-data">
       <input type="file" name="file">
       <input type="submit" value="上传">
    </form>

在建立action  很多人会不明白为什么 要写private String fileFileName  和 private String fileContentType; 注意我继承的是ActionSupport  里面有对这两个属性的配置 !

package com.upload.action;


import java.io.File;


import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;


import com.opensymphony.xwork2.ActionSupport;


public class FileUpload extends ActionSupport {
private File file;
private String fileFileName;
private String fileContentType;


@Override
public String execute() throws Exception {
// 得到上传的目录
String file_path = ServletActionContext.getServletContext().getRealPath("img");
System.out.println("文件路径"+file_path);
// 得到文件的后缀
String file_postfix = this.getFileFileName().substring(this.getFileFileName().lastIndexOf("."));
System.out.println("文件后缀"+file_postfix);
// 文件的全部信息


String file_full = file_path + File.separator+ System.currentTimeMillis() + file_postfix;
System.out.println("文件全程"+file_full);
// copy


File destFile = new File(file_full);
FileUtils.copyFile(this.getFile(), destFile);

return null;
}


public File getFile() {
return file;
}


public void setFile(File file) {
this.file = file;
}


public String getFileFileName() {
return fileFileName;
}


public void setFileFileName(String fileFileName) {
this.fileFileName = fileFileName;
}


public String getFileContentType() {
return fileContentType;
}


public void setFileContentType(String fileContentType) {
this.fileContentType = fileContentType;
}


}

然后是配置文件:

<struts>
<constant name="struts.multipart.maxSize" value="2000000"></constant>
<package name="ad" extends="struts-default">
<action name="upload" class="com.upload.action.FileUpload">

</action>
</package>


</struts>



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值