码迷,mamicode.com
首页 > Web开发 > 详细

struts2 上传单个文件

时间:2016-03-16 17:14:18      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:

1.图片上传 ENCTYPE="multipart/form-data"用于表单里有图片上传。 

 

jsp:

<input type="file" name="image">

struts.xml  

 

<action name="" class="" method="">
			<!--动态设置savePath的属性  -->
			<param name="savePath">table_images</param>
			<interceptor-ref name="fileUpload">
				  <!-- 文件过滤 -->
                <param name="allowedTypes">image/bmp,image/png,image/gif,image/jpeg</param>
                <!-- 文件大小, 以字节为单位 -->
                <param name="maximumSize">1025956</param>
			</interceptor-ref>
			<!-- 默认拦截器必须放在fileUpload之后,否则无效 -->
            <interceptor-ref name="defaultStack" />
		</action>

  action:

  // 封装上传文件域的属性
    private File image;
    // 封装上传文件类型的属性
    private String imageContentType;
    // 封装上传文件名的属性
    private String imageFileName;
    // 接受依赖注入的属性
    private String savePath;


public File getImage() {
		return image;
	}
	public void setImage(File image) {
		this.image = image;
	}
	public String getImageContentType() {
		return imageContentType;
	}
	public void setImageContentType(String imageContentType) {
		this.imageContentType = imageContentType;
	}
	public String getImageFileName() {
		return imageFileName;
	}
	public void setImageFileName(String imageFileName) {
		this.imageFileName = imageFileName;
	}
	public String getSavePath() {
		return savePath;
	}
	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}
	

  具体操作方法:

FileOutputStream fos = null;
		FileInputStream fis = null;
		try{
			ActionContext ac = ActionContext.getContext();  
			ServletContext sc = (ServletContext) ac.get(ServletActionContext.SERVLET_CONTEXT);  
			  System.out.println(sc.getRealPath("/") + getSavePath() + "\\" + getImageFileName());
	           
			  fos = new FileOutputStream(sc.getRealPath("/") + getSavePath() + "\\" + getImageFileName());
	            // 建立文件上传流
	            fis = new FileInputStream(getImage());
	            byte[] buffer = new byte[1024];
	            int len = 0;
	            while ((len = fis.read(buffer)) > 0) {
	                fos.write(buffer, 0, len);
	            }
	        } catch (Exception e) {
	            System.out.println("文件上传失败");
	            e.printStackTrace();
	        } finally {
	            close(fos, fis);
	        }

  最后不要忘记关掉输入输出流

struts2 上传单个文件

标签:

原文地址:http://www.cnblogs.com/xy-1988xcl/p/5284056.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!