数据库中的java图像存储 [英] java image store in database

查看:62
本文介绍了数据库中的java图像存储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于我的项目的问题。任何人请告诉我如何将图像路径保存到database.i已经创建上传按钮并使用FILE我已经获得图像路径。但遗憾的是我无法存储它进入database.reply我asap。这对我来说很紧张。

解决方案

图片上传jsp-servlet中的java代码

 连接  
public class DBConnection {
public 连接conn = ;
void getConnection()
{
try {
Class.forName( com.mysql.jdbc.Driver);
}
catch (ClassNotFoundException ex)
{

}
尝试 {

conn = DriverManager.getConnection( jdbc:mysql:// localhost:3306 / ImageProcessing root root);
} catch (例外情况)
{

}
}
}





数据库连接



  public   class 数据库{
static String strDB;

public DataBase( String str) throws SQLException

{
DBConnection obj = new DBConnection();
obj.getConnection();
String str1 = str;

PreparedStatement pstmt = obj.conn
.prepareStatement( insert into imagestore( ImagePath,row)值(?,?));
int i = 1;
pstmt.setString( 1 ,str1);
pstmt.setInt( 2 ,i);
pstmt.executeUpdate();

语句stmt = obj.conn.createStatement();
字符串 query = SELECT ImagePath FROM ImageStore其中row = 1;
ResultSet rs = stmt.executeQuery(query);

while (rs.next())
{
strDB = rs.getString( 1 );
}
语句stmt1 = obj.conn.createStatement();
字符串 query1 = 从ImageStore中删除行= 1\" ;
stmt1.executeUpdate(query1);


}

}





图片路径上传服务代码

  import  java.io.File; 
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;




public class FirstImage extends HttpServlet {
static String filePath;

@ Override
protected void doPost(HttpServletRequest请求,HttpServletResponse响应)
throws ServletException,IOException {
文件文件;
int maxFileSize = 5000 * 1024 ;
int maxMemSize = 5000 * 1024 ;
String fileName = null;
DBConnection obj = new DBConnection();
obj.getConnection();
ServletContext context = getServletContext();
filePath = getServletContext()。getRealPath( / images);
System.out.println(filePath);
response.setContentType( text / html);

// 验证内容类型
String contentType = request.getContentType();
if ((contentType.indexOf( multipart / form-data)> = 0 )){

DiskFileItemFactory factory = new DiskFileItemFactory();
// 将存储在内存中的最大大小
factory.setSizeThreshold( maxMemSize);
// 保存大于maxMemSize的数据的位置。
factory。 setRepository( new 文件( C:\ temp ));

// 创建新的文件上传处理程序
ServletFileUpload upload = new ServletFileUpload(factory);
// 要上传的最大文件大小。
upload.setSizeMax(maxFileSize );
尝试 {
// 解析获取文件项的请求。
列出fileItems = upload.parseRequest(request);
// 处理上传的文件项目
Iterator i = fileItems.iterator( );



while (i.hasNext())
{
FileItem fi = (的FileItem)i.next();
if (!fi.isFormField())
{
// 获取上传的文件参数
String fieldName = fi.getFieldName();
fileName = fi.getName();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
// 写文件
if (fileName.lastIndexOf( \\)> = < span class =code-digit> 0
){
file = new 文件(filePath + / +
fileName.substring(fileName.lastIndexOf( \\)));
} else {
file = new 文件(filePath + / +
fileName.substring(fileName.lastIndexOf( \\)+ 1));
}
fi.write(file);

}
}
} catch (Exception ex){
System.out.println(ex );
}

} else {
System.out.println( 没有上传文件);
}
尝试 {
new DataBase(fileName);

}

}


数据库中的
创建两个columan行(数字)和Imagepath(varchar(100))


试试这个...... :)



http://afewdoubts.blogspot.in/2013/03/upload-fileimage-in-folder-using-servlet.html [ ^ ]

i have one problem regarding my project.can anyone please tell me how to save the image path into database.i have already create the upload button and using FILE i have get the image path.but unfortunately i couldn't store it into database.reply me asap.this is urgent for me.

解决方案

Image upload java code in jsp-servlet

Connection class
public class DBConnection {
public Connection conn=null;
     void getConnection()
    {
         try {
             Class.forName("com.mysql.jdbc.Driver");
             }
         catch (ClassNotFoundException ex)
         {

         }
         try {

              conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/ImageProcessing", "root","root");
             } catch (Exception ex)
             {

             }
    }
}



Database Connection

public class DataBase {
	 static String strDB;
	
	public DataBase(String str) throws SQLException
	
	{
		DBConnection obj = new DBConnection();
		obj.getConnection();
		String str1=str;
		
		PreparedStatement pstmt = obj.conn
				.prepareStatement("insert into imagestore (ImagePath,row) values(?,?)");
		int i=1;
		pstmt.setString(1, str1);
		pstmt.setInt(2,i );
		pstmt.executeUpdate();
		
		Statement stmt = obj.conn.createStatement();
	      String query = "SELECT ImagePath FROM ImageStore where row=1";
	      ResultSet rs =  stmt.executeQuery(query);
	  
	      while(rs.next())
	      {
	    	  strDB=rs.getString(1);
	      }
	      Statement stmt1 = obj.conn.createStatement();
	      String query1 = "delete from ImageStore where row=1";
	  stmt1.executeUpdate(query1);
	      

	}

}



Image pathUpload servled code

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;




public class FirstImage extends HttpServlet{
	  static  String filePath ;

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		   File file ;
		   int maxFileSize = 5000 * 1024;
		   int maxMemSize = 5000 * 1024;
		   String fileName = null;
		   DBConnection obj = new DBConnection();
			obj.getConnection();
		   ServletContext context = getServletContext();
		   filePath =  getServletContext().getRealPath("/images");
		   System.out.println(filePath);
		   response.setContentType("text/html");
		  
		   // Verify the content type
		   String contentType = request.getContentType();
		   if ((contentType.indexOf("multipart/form-data") >= 0)) {

		      DiskFileItemFactory factory = new DiskFileItemFactory();
		      // maximum size that will be stored in memory
		      factory.setSizeThreshold(maxMemSize);
		      // Location to save data that is larger than maxMemSize.
		      factory.setRepository(new File("C:\temp"));

		      // Create a new file upload handler
		      ServletFileUpload upload = new ServletFileUpload(factory);
		      // maximum file size to be uploaded.
		      upload.setSizeMax( maxFileSize );
		      try{ 
		         // Parse the request to get file items.
		         List fileItems = upload.parseRequest(request);
		         // Process the uploaded file items
		         Iterator i = fileItems.iterator();
		         
		        
		        
		         while ( i.hasNext () ) 
		         {
		            FileItem fi = (FileItem)i.next();
		            if ( !fi.isFormField () )	
		            {
		            // Get the uploaded file parameters
		            String fieldName = fi.getFieldName();
		             fileName = fi.getName();
		            boolean isInMemory = fi.isInMemory();
		            long sizeInBytes = fi.getSize();
		            // Write the file
		            if( fileName.lastIndexOf("\\") >= 0 ){
		            file = new File( filePath +"/"+ 
		            fileName.substring( fileName.lastIndexOf("\\"))) ;
		            }else{
		            file = new File( filePath +"/"+ 
		            fileName.substring(fileName.lastIndexOf("\\")+1)) ;
		            }
		            fi.write( file ) ;
		            
		            }
		         }
		         }catch(Exception ex) {
		         System.out.println(ex);
		      }
		      
		   }else{
		     System.out.println("no file uploaded");
		   }
		   try {
			new DataBase(fileName);

          }

}


in database create two columan row(number) and Imagepath(varchar(100))


try this...:)

http://afewdoubts.blogspot.in/2013/03/upload-fileimage-in-folder-using-servlet.html[^]


这篇关于数据库中的java图像存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆