`

struts2 中的文件上传

 
阅读更多
struts.xml
<!-- 配置文件上传的参数 -->
<constant name="struts.multipart.saveDir" value="/tmp"/>
<constant name="struts.multipart.maxSize" value="100000000"/>

<!-- 配置处理文件上传的Action -->
<action name="uploadPro" class="com.coinv.mts.action.UploadAction">
<!-- 动态设置Action的属性值 -->
<param name="savePath">/uploadFiles</param>
<!-- 配置Struts 2默认的视图页面 -->
<result>/JSP/success.jsp</result>
</action>


action

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

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class UploadAction extends ActionSupport {

private static final long serialVersionUID = 1L;

private String title;
private File upload;
private String uploadContentType;
private String uploadFileName;
private String savePath;

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

public File getUpload() {
return upload;
}

public void setUpload(File upload) {
this.upload = upload;
}

public String getUploadContentType() {
return uploadContentType;
}

public void setUploadContentType(String uploadContentType) {
this.uploadContentType = uploadContentType;
}

public String getUploadFileName() {
return uploadFileName;
}

public void setUploadFileName(String uploadFileName) {
this.uploadFileName = uploadFileName;
}

public String getSavePath() {
return ServletActionContext.getServletContext().getRealPath("/WEB-INF/" + savePath);
}

public void setSavePath(String savePath) {
this.savePath = savePath;
}
public String execute() throws Exception {
FileOutputStream fos = new FileOutputStream(getSavePath() + "\\" + getUploadFileName());
FileInputStream fis = new FileInputStream(getUpload());
byte[] buffer = new byte[1024];
int len = 0;
while((len = fis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
return SUCCESS;
}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics