日期:2014-05-16  浏览次数:21065 次

Servlet 上传文件流到Mysql
Mysql数据库建表语句:

CREATE TABLE `photo` (

  `id` int(11) NOT NULL AUTO_INCREMENT,

  `title` varchar(100) NOT NULL,

  `image` blob NOT NULL,

  PRIMARY KEY (`id`)

) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1







//DBClassMysql.java  自己添加mysql的java驱动,要不会报错的

package com.abin.upload.image;



import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.Statement;



public final class DBClassMysql {

//Mysql

private static String driver="com.mysql.jdbc.Driver";

private static String url="jdbc:mysql://localhost:3306/test";

private static String user="root";

private static String password="";


public DBClassMysql ()throws ClassNotFoundException{


}


//Mysql

public static Connection getMysql(){

Connection conn=null;

try{

if(null==conn||conn.isClosed()){

Class.forName(driver).newInstance();

conn=DriverManager.getConnection(url,user,password);

}

}catch(Exception e){

e.printStackTrace();

throw new RuntimeException(e);

}

return conn;

}

}



//ImageServlet.java  保存文件流的servlet
package com.abin.upload.image;



import java.io.IOException;

import java.io.InputStream;

import java.sql.Connection;

import java.sql.PreparedStatement;

import java.util.Iterator;

import java.util.List;



import javax.servlet.ServletConfig;

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 ImageServlet extends HttpServlet {



public void init(ServletConfig config) throws ServletException {

super.init(config);

}



public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

super.doPost(request, response);

}



public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

Connection conn = null;

PreparedStatement ps=null;

String title = null;

int imageLength = 0;

byte[] buffer = new byte[imageLength];



InputStream in = null;

int total = 0;

int once = 0;

DiskFileItemFactory factory = new DiskFileItemFactory();

ServletFileUpload file = new ServletFileUpload(factory);

try {

List lst = file.parseRequest(request);

Iterator it = lst.iterator();

while (it.hasNext()) {

FileItem fileItem = (FileItem) it.next();

if (fileItem.isFormField()) {

title = fileItem.getString("UTF-8");

System.out.println("表单数据的名称是:" + fileItem.getFieldName()

+ ":表单的内容是:" + fileItem.getString("UTF-8"));

} else {

if (fileItem.getName() != null

&& !fileItem.getName().equals("")) {

imageLength = Integer.parseInt(String.valueOf(fileItem

.getSize()));

in =