Struts2文件(图片)上传及页面显示

该博客介绍了如何使用Struts2框架进行文件上传操作,特别是图片。首先,需要引入commons-io和commons-fileupload两个jar包。然后,通过创建UploadFile action,设置上传文件的属性,并实现上传方法,将文件保存到指定目录。如果上传成功,会返回消息提示。最后,可以在页面上展示上传的图片。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、导入文件上传的两个jar包

commons-io-2.5.jar
commons-fileupload-1.3.2.jar

2、jsp上传页面代码

<form action="FileUpload2" enctype="multipart/form-data" method="post" >  
	上传文件:<input type="file" name="image"><br/>  
             	<input type="submit" value="提交"/>  
</form>

3、action中的代码
public class UploadFile extends ActionSupport{
	
    private static final long serialVersionUID = 1L;
	
    private File image; //上传的文件
    private String imageFileName; //文件名称
    private String imageContentType; //文件类型
	
    public File getImage() {
		return image;
	}
	public void setImage(File image) {
		this.image = image;
	}
	public String getImageFileName() {
		return imageFileName;
	}
	public void setImageFileName(String imageFileName) {
		this.imageFileName = imageFileName;
	}
	public String getImageContentType() {
		return imageContentType;
	}
	public void setImageContentType(String imageContentType) {
		this.imageContentType = imageContentType;
	}
    
    public String upload(){
    	String realpath = ServletActionContext.getServletContext().getRealPath("/images");
        System.out.println("realpath: "+realpath);
        if(image != null){
        	File savefile = new File(new File(realpath), imageFileName);
        	System.out.println(savefile);
        	System.out.println(savefile.getParentFile());
        	if(savefile.getParentFile().exists()){
        		try {
					savefile.getParentFile().mkdirs();
					FileUtils.copyFile(image, savefile);
				} catch (IOException e) {
					e.printStackTrace();
				}
        		ActionContext.getContext().put("message", "文件上传成功");
        	}
        }
        /**
         * 若要存入数据库
         * fileName是在entity实体类中声明存放文件名称的变量
         * yu.setFileName(imageFileName) 这样将文件名称存入数据库
         * 文件路径为:savefile
         */
        return "success";
    }
}

3、在页面显示

	<img src="${pageContext.request.contextPath}/images/${fileName}" /><br />
         或者
    	<img src="${pageContext.request.contextPath }/images/<s:property value="fileName"/>" />



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值