SSH项目上传图片并把图片路径存放在数据库, 及其图片的显示

本文介绍如何在SSH项目中实现图片上传,通过设置form的enctype属性为"multipart/form-data",确保图片文件正确编码,同时将图片路径保存在数据库中。

页面设置:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. <form method="post" enctype="multipart/form-data">   
  2.   
  3. <input type="file" name="upload" />  

enctype属性:

    enctype 属性规定在发送到服务器之前应该如何对表单数据进行编码。

    默认地,表单数据会编码为 "application/x-www-form-urlencoded"。就是说,在发送到服务器之前,所有字符

都会进行编码(空格转换为 "+" 加号,特殊符号转换为 ASCII HEX 值)。

               


Multipart/form-data?

     Multipart/form-data是上传文件的一种方式.
     Multipart/form-data其实就是浏览器用表单上传文件的方式.最常见的情境是:在写邮件时,向邮件后添加附
件,附件通常使用表单添加,也就是用multipart/form-data格式上传到服务器.在上传图片的时候也是用这种格式上
传的.

Action:
//编辑图片投票选项
	public String publishImageVoteContext() throws IOException{
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession();
		ImageVote imageVote = (ImageVote) session.getAttribute("imageVote");
		ImageVoteContext voteContext;
		for (int i = 0; i < upload.length; i++){
			voteContext = new ImageVoteContext();
			if(upload != null){  
	            // 将图片上传到服务器上.  
	            // 获得上传图片的服务器端路径.  
	            String path = ServletActionContext.getServletContext().getRealPath(  
	                    "/images");  
	            // 创建文件类型对象:  
	            File diskFile = new File(path + "//" + uploadFileName[i]);  
	            // 文件上传:  
	            FileUtils.copyFile(upload[i], diskFile);  
	            voteContext.setImageVoteContext("images/" + uploadFileName[i]);
	        }  
			System.out.println(uploadFileName[i] + " " + imageVoteContextDescription[i]);
			voteContext.setImageVote(imageVote);
			voteContext.setImageVoteContextDescription(imageVoteContextDescription[i]);
			voteContext.setImageVoteContextCount(0);
			adminService.publishImageVoteContext(voteContext);
		}
		return SUCCESS;
	}


//JSP页面得到图片:
因为我们已经把图片路径存放在数据库里了,上传的图片的目录在tomcat服务器的 webapps下的你的项目的images文件夹里,所以我们可以按照下面的代码直接取出图片
 <tr>
  			 	<td>第<%=i + 1 %>项:</td>
  			 	<td><img src="<%=imageVoteContexts.get(i).getImageVoteContext() %>" /></td>
  			 </tr>



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值