六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 48|回复: 0

在struts2中实现文件的上传

[复制链接]

升级  24%

22

主题

22

主题

22

主题

秀才

Rank: 2

积分
86
 楼主| 发表于 2013-1-15 02:56:05 | 显示全部楼层 |阅读模式
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了。经过刷新可以看到你上传的文件了。

个人学习,仅供参考
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表