Struts2方式的文件上传.txt

private String username;

private String password;

 

private File file;

private String fileFileName;

private String fileContentType;

 

public String execute() throws Exception {

InputStream is = new FileInputStream(file);

String root = servletActionContext.getRequest().getRealPath("/upload"); //不可避免的与servlet偶合

File destFile = new File(root, this.getFileFileName());

OutputStream os = new FileOutputStream();

byte[] buffer = new byte[400];

int length = 0;

while((length = is.read(buffer)) > 0) {

os.write(buffer, 0, length);

}

is.close();

os.close();

return SUCCESS;

}

 

以上情况传中文文件时会乱码,可在struts.xml中设置编码过滤器

<constant name="struts.i18n.encoding" value="gbk"></constant>

 

struts2文件上传时是将文件先放在一个临时目录中,再写入到指定目录中,且真正上传完之后会删除临时目录中的临时文件。

<constant name="struts.multipart.saveDir" value="c:/"></constant>

 

上传文件大小,默认2M

<constant name="struts.multipart.maxSize" value="1024"></constant>

 

默认为action

<constant name="struts.action.extension" value="do"></constant>

 

 

限定用户上传文件的数量

jsp中的file的name要都为file;

 

private List<File> file; //也可以用数组,因为底层两者都是一样的,建议用List

private List<String> fileFileName;

private List<String> fileContentType;

 

public String execute() throws Exception

{

for (int i = 0; i < file.size(); ++i)

{

InputStream is = new FileInputStream(file.get(i));

 

String root = ServletActionContext.getRequest().getRealPath(

"/upload");

 

File destFile = new File(root, this.getFileFileName().get(i));

 

OutputStream os = new FileOutputStream(destFile);

 

byte[] buffer = new byte[400];

 

int length = 0;

 

while ((length = is.read(buffer)) > 0)

{

os.write(buffer, 0, length);

}

 

is.close();

 

os.close();

}

 

return SUCCESS;

 

}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值