文件,图片上传

     最近看到了以前写的一个代码,使用ServletFileUpload上传文件或者图片,然后想想,代码都快丢了,就留个博客记录下吧!

前端index.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>文件上传</title>
</head>
<body>
	<form action="LunboAction" method="post" enctype="multipart/form-data">
		本地目录:<input type="file" name="uploadFile" >
		<input type="submit" value="上传头像">
	</form>
</body>
</html>
Servlet类:LunboAction中的方法

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		HttpSession session = request.getSession();
		// 判断上传表单是否为multipart/form-data类型 
		if(ServletFileUpload.isMultipartContent(request)) {
			try {
				 // 1. 创建DiskFileItemFactory对象(文件处理工厂),设置缓冲区大小和临时文件目录
				DiskFileItemFactory factory = new DiskFileItemFactory();
				System.out.println("默认的临时文件夹:"+System.getProperty("java.io.tmpdir"));
				
				// 2. 创建ServletFileUpload对象(文件上传处理器),并设置上传文件的大小限制。  
				ServletFileUpload sfu = new ServletFileUpload(factory);
				sfu.setSizeMax(10*1024*1024);//10M
				sfu.setHeaderEncoding("utf-8");
				
				// 3 调用ServletFileUpload.parseRequest方法解析request对象,得到一个保存了所有上传内容的List对象。  
				List<FileItem> fileItemList = (List<FileItem>)sfu.parseRequest(new ServletRequestContext(request));
			        Iterator<FileItem> fileItems = fileItemList.iterator(); 
			        // 4. 遍历list,每迭代一个FileItem对象,调用其isFormField方法判断是否是上传文件  
			        while(fileItems.hasNext()) {
			    	 FileItem fileItem = fileItems.next();
			    	 if(fileItem.isFormField()) {
			    		 String name = fileItem.getFieldName();
			    		 String value = fileItem.getString("utf-8");
			    		 System.out.println(name+"="+value);
			    	 } else {
			    		 //信息的文件格式
			    		 String fileName = fileItem.getName();
			    		 System.out.println("原文件名:"+fileName);
			    		 String suffix = fileName.substring(fileName.lastIndexOf('.'));
			    		 System.out.println("扩展名:"+suffix);
			    		 
			    		 //新文件名
			    		 String newFileName = new Date().getTime()+suffix;
			    		 System.out.println("新文件名:"+newFileName);
			    		 
			    		 //5调用fileItem的write方法,写入文件
			    		 File file = new File("D:/mywork/20170814ImageUpload/WebContent/touxiang/"+newFileName);
			    		 System.out.println(file.getAbsolutePath());
			    		 fileItem.write(file);
			    		 
			    		 //6,调用fileItem的delete方法删除临时文件
			    		 fileItem.delete();
			    		 //7 存到数据库,保存源文件名称2,保存相对路径
			    		 try {
							Class.forName("com.mysql.jdbc.Driver");
							String url = "jdbc:mysql://localhost:3306/test";
							String name = "root";
							String password = "root";
							Connection conn = DriverManager.getConnection(url, name, password);
							
							String Sql = "INSERT INTO t_touxiang(image_path,user_id,old_name)VALUES(?,?,?)";
							PreparedStatement ps = conn.prepareStatement(Sql);
							ps.setString(1, newFileName);
							ps.setInt(2, 1111);
							ps.setString(3, fileName);
							int rows = ps.executeUpdate();
							if(rows > 0) {
								session.setAttribute("image_name", fileName);
								session.setAttribute("image_path","touxiang/"+newFileName);
								response.sendRedirect(request.getContextPath()+"/readPicture");
								
							} else {
								response.sendRedirect("http://www.baidu.com");
							}
						} catch (Exception e) {}
			    	 }
			     }
			} catch (Exception e) {			}
		}
	}
然后后台的Servlet读取图片信息

protected void service(HttpServletRequest request, HttpServletResponse response)  
	        throws ServletException, IOException {  
		String result = null;
		try {
			int id =2;
			String sqlString="SELECT image_path FROM t_touxiang WHERE id=?";
			Class.forName("com.mysql.jdbc.Driver");
			String url = "jdbc:mysql://localhost:3306/test";
			String name = "root";
			String password = "root";
			Connection conn = DriverManager.getConnection(url, name, password);
			PreparedStatement ps = conn.prepareStatement(sqlString);
			ps.setInt(1, id);
			ResultSet urs = ps.executeQuery();
			while(urs.next()) {
				System.out.println(urs.getString("image_path"));
				result = urs.getString("image_path");
			}
			
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		request.setAttribute("txt", result);
		request.getRequestDispatcher("/ShowImage.jsp").forward(request, response);
	}
前台展示图片,ShowImage.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
<%
	String path = (String)request.getAttribute("txt");
%>
</head>
<body>
	    <span style="white-space:pre"></span><div>  
        	<form action="" method="post" enctype="multipart/form-data">
                <img src="./touxiang/<%=path %>"  width="200" height="200">
       		</form>  
        </div>  
</body>
</html>



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值