Struts文件上传与下载详解_上传单个文件
发布日期:2021-05-14 13:06:27 浏览次数:21 分类:精选文章

本文共 2133 字,大约阅读时间需要 7 分钟。

        大家都知道Servlet上传文件的时候用的是commons-fileupload插件上传的,但是过程极其的麻烦,同样Struts2也有自带的文件上传,但是过程比Servlet里面的简单了不少,接下来请大家看演示:

      我们现在先建一个表单用于上传文件:

  

          这个很简单,主要就是用的Struts的标签展示出来的,这里不多做解释,然后我们再写个UploadAction来处理这个文件上传:

package org.web;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import org.apache.struts2.ServletActionContext;import com.opensymphony.xwork2.ActionSupport;public class UploadAction extends ActionSupport {	private File upload;                       //封装上传文件的属性(单个)	private String uploadContentType;          //封装上传文件的类型(单个)	private String uploadFileName;             //封装上传文件的名称(单个)	private String savePath;                   //获取文件上传的路径(单个)		//实现文件的单个上传	public String execute() throws IOException{		byte[]by=new byte[1024];		//获取物理路径"/upload"		String path=ServletActionContext.getServletContext().getRealPath(savePath);		FileInputStream in = new FileInputStream(getUpload());		FileOutputStream out=new FileOutputStream(path+"\\"+getUploadFileName());		int i=in.read(by);		while(i>0){			out.write(by,0,i);			i=in.read(by);		}		in.close();		out.flush();		out.close();		return SUCCESS;	}					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 savePath;	}	public void setSavePath(String savePath) {		this.savePath = savePath;	}	}
       需要注意的是:由于文件上传到了/upload目录下面,所以咱们得先在WebRoot下面创建一个文件夹“upload”,上传的所有的文件都在这个目录下面。

       接着我们来配置struts.xml文件:

/upload
/upload_suc.jsp
        然后我们就可以发布运行了。

        注意:

   1.execute的方法千万别写错,要不然上传不到服务器upload里面。

    2.UploadAction里面File upload,此处的upload必须要和jsp里面的name的值一样

   3.文件类型命名:upload+ContentType

     

上一篇:Struts文件上传与下载详解 _上传多个文件
下一篇:hibernate+struts2整合jar包冲突

发表评论

最新留言

第一次来,支持一个
[***.219.124.196]2025年04月13日 20时41分45秒