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

3722

被折叠的 条评论
为什么被折叠?



