djlijian 发表于 2013-1-28 19:28:23

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

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了。经过刷新可以看到你上传的文件了。

个人学习,仅供参考
页: [1]
查看完整版本: 在struts2中实现文件的上传