Struts2 文件上传

1.文件上传Action类

package com.zhanggaosong.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.UUID;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class UploadAction extends ActionSupport {

private String picName;
private File pic; // 上传文件的文件本身
private String picFileName; // 上传文件的原始文件名
private String picContentType; // 上传文件的文件类型

public String getPicName() {
return picName;
}

public void setPicName(String picName) {
this.picName = picName;
}

public File getPic() {
return pic;
}

public void setPic(File pic) {
this.pic = pic;
}

public String getPicFileName() {
return picFileName;
}

public void setPicFileName(String picFileName) {
this.picFileName = picFileName;
}

public String getPicContentType() {
return picContentType;
}

public void setPicContentType(String picContentType) {
this.picContentType = picContentType;
}

@Override
public String execute() throws Exception {

/**
* 处理文件上传
*/

String uploadPath = ServletActionContext.getServletContext()
.getRealPath("/upload");

String fileName = UUID.randomUUID().toString()
+ picFileName.substring(picFileName.lastIndexOf("."));

System.out.println(uploadPath + "/" + fileName);

System.out.println("文件名:"+fileName);

FileInputStream is = new FileInputStream(pic);

FileOutputStream os = new FileOutputStream(uploadPath + "/" + fileName);

byte[] buff = new byte[1024];
int hasRead = 0;
while((hasRead = is.read(buff))>0){
os.write(buff,0,hasRead);
}
is.close();
os.close();

/**
* 将文件名放到数据库中去
*/

return SUCCESS;
}

}

2.配置Struts.xml文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="true" />

<package name="uploadAction" namespace="/" extends="struts-default">
<action name="uploadAction" class="com.zhanggaosong.action.UploadAction">
<result>/success.jsp
</result>
</action>
</package>
</struts>

3.文件上传页面

<body>
<h2>文件上传</h2>
<s:actionmessage />
<s:form action="uploadAction" method="post"
enctype="multipart/form-data">
<table>
<tr>
<td><s:file name="pic" label="请选择上传的文件:" /></td>
</tr>
<tr>
<td><s:submit value="上传" /></td>
</tr>
</table>
</s:form>
</body>

转载于:https://www.cnblogs.com/zhanggaosong/archive/2013/03/12/2955105.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值