struts2实现文件上传和下载

来源:互联网 发布:js百叶窗源码 编辑:程序博客网 时间:2024/06/16 14:06

action 

private File upload;//上传文件属性

private String uploadFileName;//上传文件名称
private String uploadContentType;//上传文件类型
private String uploadPath;
@Override
public String execute() throws Exception {
byte[] bu=new byte[1024];
FileInputStream fis=new FileInputStream(this.getUpload());
FileOutputStream fos=new FileOutputStream(getUploadPath()+"/"+this.getUploadFileName());
int length=fis.read(bu);
while(length>0){
fos.write(bu);
length=fis.read(bu);
}
fis.close();
fos.flush();
fos.close();
return SUCCESS;
}


public File getUpload() {
return upload;
}
public void setUpload(File upload) {
this.upload = upload;
}
public String getUploadFileName() {
return uploadFileName;
}
public void setUploadFileName(String uploadFileName) {
this.uploadFileName = uploadFileName;
}
public String getUploadContentType() {
return uploadContentType;
}
public void setUploadContentType(String uploadContentType) {
this.uploadContentType = uploadContentType;
}
public String getUploadPath() {
return ServletActionContext.getServletContext().getRealPath("UpLoad");
}
public void setUploadPath(String uploadPath) {
this.uploadPath = uploadPath;

}

jsp页面

<form action="upload" enctype="multipart/form-data" method="post">
    点击上传<input type="file" name="upload"><br>
    <input type="submit" value="上传">
    </form>
     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~<br>
    upload:  ${upload }<br>
    uploadFileName:  ${uploadFileName }<br>
    uploadContentType:  ${uploadContentType }<br>

Struts.xml配置文件为

<!-- 文件上传 -->
<action name="upload" class="com.sheng.action.UpLoadAction">
<result name="success">/upload.jsp</result>
</action>

原创粉丝点击