Javaweb上传图片途径到数据库

Javaweb上传图片途径到数据库

结果如下

首先建立数据库存放上传图片路径数据库属性用varchar(),大小差不多设置为 255。

数据库连接在这里就不多说了

jsp页面

<body>
	<form action="${pageContext.request.contextPath}/uppicture" method="post"  enctype="multipart/form-data" >
	 昵称:<input type="text" name="name"><br>
            <div>
             	 <img src="${image_path}" width="200" height="200">
             </div>
              头像:<input type="file" name="uploadFile"> 
        <input type="submit" value="上传头像"/>
   </form>

Dao.java添加到数据库add方法

package com.picture.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import com.imooc.db.DButil;
import com.picture.Bean.Picture;
public class Dao {
	private Connection conn;
	private PreparedStatement ps;
	public void add(Picture picture){
		
        try {
        	conn=DButil.getConnection();
            String sql="insert into picture_2(name,picturepath)"+" values (?,?)" ;
			ps=conn.prepareStatement(sql);
			ps.setString(1,picture.getName());
			ps.setString(2,picture.getPicturepath());
			  ps.execute();
		} catch (SQLException e) {
			e.printStackTrace();
		}
      
	}
	
}

upServlet.java,Servlet文件处理数据

package com.picture.servlet;
import com.picture.Bean.Picture;
import com.picture.dao.Dao;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Calendar;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class upServlet
 */
//@WebServlet("/upServlet")
public class upServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//通知客户端以utf-8编码进行解析
		       
				response.setContentType("text/html;charset=utf-8");
				//数据库以UTF-8编码解析数据
				request.setCharacterEncoding("UTF-8");
				
				String name=null;
			
			    Picture picture=new Picture();
			    Dao dao=new Dao();
				//判断请求是否为multipar请求
				if(!ServletFileUpload.isMultipartContent(request))
				{
					throw new RuntimeException("当前请求不支持文件上传");
				}
				//为基于磁盘的文件项创建一个FileItem工厂
				DiskFileItemFactory factory = new DiskFileItemFactory();
				//设置临时文件的边界值,大于该值时,上传文件会先保存在临时文件中,否则,上传文件将直接写入到内存
				//单位:字节,设置边界值1M,一字节=1024M;
				factory.setSizeThreshold(1024*1024*1);
				//设置文件临时储存
				String temppath=this.getServletContext().getRealPath("/temp");
				File temp=new File(temppath);
				factory.setRepository(temp);
				//创建一个新的文件上传处理程序
				ServletFileUpload upload = new ServletFileUpload(factory);
				//设置每一个item的头部字符编码,其可以解决文件名中文乱码问题;
				upload.setHeaderEncoding("UTF-8");
				//设置单个文件的最大边界值(这里是2M)
				upload.setFileSizeMax(1024*1024*2);
				//设置一次上传所有文件总和的最大值(对上传多个文件起作用,这里最大为5M)
				upload.setSizeMax(1024*1024*5);
				//解析请求,获取所有的item
				try {
				//
					//调用ServletFileUpload.parseRequest方法解析request对象,
					//得到一个保存了所有上传内容的List对象。
				List <FileItem> items = upload.parseRequest(request);
				//遍历
				for(FileItem item:items){
				//若item为普通表单项
					if(item.isFormField()){
					//获取表单中属性名称
					String fieldName = item.getFieldName();
					if(fieldName.equals("name")){
					//获取表单属性的值
					 name=item.getString("UTF-8");
					}
					System.out.println(fieldName+"="+name);
				//若	item为文件表单项
					}else{
					//获取文件大小
					long size=item.getSize();
					//获取文件类型
					String contentType = item.getContentType();
					//获取上传文件原始名字
					String fileName = item.getName();
					System.out.println("文件大小:"+size);
					System.out.println("文件的类型:"+contentType);
					//System.out.println("文件的名称:"+fileName);
				    //获取文件名,处理获取到的上传文件的文件名的路径部分,只保留文件名部分
					if(fileName.contains("\\"))
		            {
		                //如果包含则截取字符串
						fileName=fileName.substring(fileName.lastIndexOf("\\")+1);
		            }
					//设置文件名,因为同名的文件会覆盖,所以要修饰文件名,设置毫秒+文件名
					fileName=System.currentTimeMillis()+fileName;
					System.out.println("文件的名称:"+fileName);
					//获取输入流,其实有上传文件的内容
					InputStream inputStream = item.getInputStream();
					
					//String parent=this.getServletContext().getRealPath("./images");
					String path="E:\\picture-up";
					File dirFile=new File(path);
					if(!dirFile.exists()){
						//创建多级目录mkdirs()
						dirFile.mkdir();
					}
					//创建目录文件,将来用于保存上传文件
					File file = new File(path, fileName);
					//创建文件输出流
					OutputStream os=new FileOutputStream(file);	
					//把输入流中的数据写入到输出流
					int len=0;
					byte[] buf=new byte[1024];
					while((len=inputStream.read(buf))!=-1){
						os.write(buf, 0, len);
					}
                   //图片上传到之后的路径
					path="E:\\picture-up"+"\\"+fileName;
					picture.setName(name);
					picture.setPicturepath(path);
					System.out.println(picture.getName()+"----"+picture.getPicturepath());
                   //调用Dao中的add()方法
					dao.add(picture);
					os.close();
					inputStream.close();
					//删除临时文件
					item.delete();
					}
				}	
					
				} catch (FileUploadException e) {
					
					e.printStackTrace();
				}
			}

	}


web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>picture-up</display-name>
  <servlet>
  		<servlet-name>uppicture</servlet-name>
  		<servlet-class>com.picture.servlet.upServlet</servlet-class>
  </servlet>
  <servlet-mapping>
  		<servlet-name>uppicture</servlet-name>
  		<url-pattern>/uppicture</url-pattern>
  </servlet-mapping>
</web-app>

好了,希望能帮到你们

 

  • 15
    点赞
  • 130
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
JavaWeb上传图片数据库需要进行以下几个步骤: 1.在数据库中创建表,其中包含一个用于存储图片的BLOB类型的字段。 2.在JSP页面中添加一个表单,用于上传图片。 3.在Servlet中获取表单数据,包括上传的图片。 4.将图片转换为字节数组,并将其存储到数据库中。 5.在JSP页面中显示从数据库中检索到的图片。 以下是一个简单的示例代码: 1.创建数据库表 ```sql CREATE TABLE `image` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) DEFAULT NULL, `data` longblob, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; ``` 2.添加上传表单 ```html <form action="upload" method="post" enctype="multipart/form-data"> <input type="file" name="file"> <input type="submit" value="Upload"> </form> ``` 3.处理上传请求 ```java @WebServlet("/upload") @MultipartConfig public class UploadServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { InputStream inputStream = null; OutputStream outputStream = null; Connection connection = null; PreparedStatement statement = null; try { Part filePart = request.getPart("file"); if (filePart != null) { inputStream = filePart.getInputStream(); Class.forName("com.mysql.jdbc.Driver"); connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "password"); statement = connection.prepareStatement("INSERT INTO image (name, data) values (?, ?)"); statement.setString(1, filePart.getName()); statement.setBlob(2, inputStream); statement.executeUpdate(); } response.sendRedirect("index.jsp"); } catch (Exception e) { e.printStackTrace(); } finally { if (inputStream != null) { inputStream.close(); } if (outputStream != null) { outputStream.close(); } if (statement != null) { statement.close(); } if (connection != null) { connection.close(); } } } } ``` 4.从数据库中检索图片并显示 ```java @WebServlet("/image") public class ImageServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Connection connection = null; PreparedStatement statement = null; ResultSet resultSet = null; OutputStream outputStream = null; try { int id = Integer.parseInt(request.getParameter("id")); Class.forName("com.mysql.jdbc.Driver"); connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "password"); statement = connection.prepareStatement("SELECT * FROM image WHERE id = ?"); statement.setInt(1, id); resultSet = statement.executeQuery(); if (resultSet.next()) { Blob blob = resultSet.getBlob("data"); byte[] bytes = blob.getBytes(1, (int) blob.length()); response.setContentType("image/jpeg"); outputStream = response.getOutputStream(); outputStream.write(bytes); } } catch (Exception e) { e.printStackTrace(); } finally { if (outputStream != null) { outputStream.close(); } if (resultSet != null) { resultSet.close(); } if (statement != null) { statement.close(); } if (connection != null) { connection.close(); } } } } ```
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值