电子相册系统(五)添加图片

1. 功能说明

在添加图片之前,我们需要弹出个带有蒙板的提示框,样式如下。当然我们上传图片的名字不能重复,图片还要放在服务器的指定文件夹下。上传成功之后,我们还要在页面中显示了出来。


2. 构思实现

1)        要想弹出带有蒙板的提示框,那么我们就可借助jQuery的方法来实现,而提示框上的那些,我们需要自己设计个<div/>的标签来实现。

2)        图片的上传,需要用户添加图片的名称,为了避免重复,我们采用UUID的方法后台全名图片名字。一旦用户上传图片成功之后,不仅要写入数据库,同时要PrintWriter的方法,将图片写出到客户端。

3. 具体实现

1)        在html的页面中,我们要设计个<div/>,其中包含了提示框要显示的文本框和相应的信息。

<div id="uploadDiv" title="上传图片" style="display:none">
<form action="proUpload" method="post"
	enctype="multipart/form-data"
	target="hideframe">
<table width="400" border="0" cellspacing="1" cellpadding="10">
<tr>
	<td height="25">图片标题:</td>
	<td><input id="title" name="title" type="text" /></td>
</tr>
<tr>
	<td height="25">浏览图片:</td>
	<td><input id="file" name="file" type="file" /></td>
</tr>
<tr>
	<td colspan="2" align="center">
	<input type="submit" value="上传" />
	<input type="reset" value="重设" />
	</td>
</tr> 
</table>
</form>
</div>

2)        对于蒙板的显示,我们是通过jQuery来实现的,所以我们还要写个关于这个实现的方法。注意这里调用的标签名就是uploadDiv。

// 打开上传窗口
function openUpload()
{

	$("#uploadDiv").show()
		.dialog(
		{
			modal: true,
			title: '上传照片',
			resizable: false,
			width: 428,
			height: 220,
			overlay: {opacity: 0.5 , background: "black"}
		});
}

3)        接下来就来到了实现上传图片的核心地方了,那就是我们要使用Java的I/O来实现文件的上传,还有就是文件的读取。

@WebServlet(urlPatterns="/proUpload")
public class ProUploadServlet extends BaseServlet
{

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		
		Iterator iter = null;
		String title = null;
		response.setContentType("text/html;charset=gbk");
		//获取输出流
		PrintWriter out = response.getWriter();
		try
		{
			//使用Upload处理上传
			FileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			List items = upload.parseRequest(request);
			iter = items.iterator();
			//遍历每个表单控件对应的内容
			while (iter.hasNext())
			{
				FileItem item = (FileItem)iter.next();
				//如果该项是普通表单域
				if (item.isFormField())
				{
					String name = item.getFieldName();
					if(name.equals("title"))
					{
						title = item.getString("gbk");
					}
				}
				//如果是需要上传的文件
				else
				{
					String user = (String) request.getSession().getAttribute("curUser");
					String serverFileName = null;
					//返回文件名
					String fileName = item.getName();
					//取得文件后缀
					//String suffix = fileName.substring(fileName.lastIndexOf("."));
					//返回文件类型
					String contentType = item.getContentType();
					//只允许上传jpg、gif、png图片
					if(contentType.equals("image/pjpeg")
							|| contentType.equals("image/gif")
							|| contentType.equals("image/jpeg")
							|| contentType.equals("image/png"))
					{
						InputStream input = item.getInputStream();
						serverFileName = UUID.randomUUID().toString();
						//System.out.println("filename:"+fileName);
						//判断文件夹是否存在
						createFile(request,out);
						
						FileOutputStream output = new FileOutputStream(
								getServletContext().getRealPath("/")
								+ "uploadfiles\\" + serverFileName );
								//+ suffix);
						byte[] buffer = new byte[1024];
						int len = 0;
						while ((len = input.read(buffer)) > 0)
						{
							output.write(buffer, 0, len);
						}
						input.close();
						output.close();
						as.addPhoto(user, title, fileName, serverFileName);
								//+ suffix);
						out.write("<script type='text/javascript'>"
								+ "parent.callback('恭喜你,文件上传成功!')"
								+ "</script>");
					}
					else
					{
						out.write("<script type='text/javascript'>"
								+ "parent.callback('本系统只允许上传"
								+ "JPG、GIF、PNG图片文件,请重试!')</script>");
					}
				}
			}
		}
		catch (FileUploadException e)
		{
			e.printStackTrace();
			out.write("<script type='text/javascript'>"
					+ "parent.callback('处理上传文件出现错误,请重试!')"
					+ "</script>");
		}
		catch(AlbumException ex)
		{
			ex.printStackTrace();
		} 
	}
	
	/**
	 * 创建文件夹uploadfiles
	 * @param request
	 * @param out
	 */
	public void createFile(HttpServletRequest request, PrintWriter out)
	{
		String filePath = request.getSession().getServletContext().getRealPath("uploadfiles");
		File file =new File(filePath);    
		//如果文件夹不存在则创建    
		if  (!file .exists()  && !file .isDirectory())      
		{       
		    file .mkdir();   
		} else   
		{  
			out.println("alert('系统错误!');");  
		}  
	}
}




  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值