在struts2中实现文件的上传

1,upload.jsp的简单内容:
<s:form action="fileUpload" enctype="multipart/form-data">
<s:textfield name="username" label="username:"></s:textfield><br>
<s:password name="password" label="password"></s:password><br>
<s:file name="file" label="File:"></s:file>
<s:submit></s:submit>
</s:form>

2,在struts.xml文件中配置action:
<action name="fileUpload" class="com.test.action.user.FileUploadAction">
<result name="success">/uploadResult.jsp</result>
</action>

3,FileUploadAction类的内容:

package com.test.action.user;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class FileUploadAction extends ActionSupport {

private String username;
private String password;

private File file;
//表单中传过来的file的名字
private String fileFileName;
//fileName和contentType是struts2中提供好的两个变量,要对应
private String fileContentType;

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

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

@Override
public String execute() throws Exception {
//通过File传过来的file对象获取当前文件的输入流
InputStream is = new FileInputStream(file);
//指定上传文件的路径
String path = ServletActionContext.getRequest().getRealPath("/upload");
//产生目的文件、、filenName是struts2注入进来的
File file2 = new File(path,this.getFileFileName());

OutputStream os = new FileOutputStream(file2);
//字节数组作为中间变量,输入流到输出流的转换
byte[] buffer = new byte[400];

int length = 0;

while((length = is.read(buffer)) > 0){
os.write(buffer, 0, length);
}
//最后要关闭输入,输出流
os.close();
is.close();

return SUCCESS;
}
}

4,成功页面:result.jsp如下:
<body>
username:<s:property value="username"/><br>
password:<s:property value="password"/><br>
file:<s:property value="fileFileName"/>
</body>


注意喽:
可能在你的工程下WebRoot下的upload文件夹中经过刷新找不到上传的文件。这是因为你上传的文件到了你的tomcat/webapps下面的工程了。应该在tomcat的server.xml文件下配置:<Context path="/struts2" docBase="D:\WebProject\struts2\WebRoot" reloadable="true"/>
就ok了。经过刷新可以看到你上传的文件了。

个人学习,仅供参考
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值