如何上传文件到数据库?

如何上传文件到数据库?,第1张

文件上传到数据库请参考以下示例:

<%@ page contentType="text/htmlcharset=gb2312"%>

<%@ page language="java" import="java.sql.*" %>

<%/////连接数据库

java.sql.Connection conn

java.sql.Statement stmt

java.sql.ResultSet rs1

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver")

conn=DriverManager.getConnection("jdbc:odbc:dababasename")///数据源

stmt=conn.createStatement()

%>

<%

String sqlin="insert into drawing values

File file = new File("c:/z.jpg")

long l1=file.length()

int l2=(int)l1

FileInputStream is = new FileInputStream(file)

InputStream fis=(InputStream)is

PreparedStatement ps = conn.prepareStatement("insert into images values (?,?)")

ps.setString(1,file.getName())

ps.setBinaryStream(2,fis,file.length())

ps.executeUpdate()

ps.close()

fis.close()

//将图片从数据库中提取,进行显示

//drawing字段为IMAGE类型

stmt = conn.createStatement()

rs1 = stmt.executeQuery("SELECT * FROM drawing WHERE drawing_code ='0-515' and version=3")

if (rs1.next())

{

String dim_image = rs1.getString("file_name")

byte [] blocco = rs1.getBytes("drawing")

response.setContentType("image/jpeg")

ServletOutputStream op = response.getOutputStream()

for(int i=0i<blocco.lengthi++)

{

op.write(blocco[i])

}

}

rs1.close()

%>

环境:MyEclipse 6.5 + Tomcat5.5 + Jdk 1.6 并引入 commons-fileupload-1.2.jar

jsp上传文件代码 :

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<%

String path = request.getContextPath()

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"

%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head>

<base href="<%=basePath%>">

<title>My JSP 'multiFileUpload.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">

<meta http-equiv="cache-control" content="no-cache">

<meta http-equiv="expires" content="0">

<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

<meta http-equiv="description" content="This is my page">

<!--

<link rel="stylesheet" type="text/css" href="styles.css">

-->

<script type="text/javascript">

function addMore(){

var td=document.getElementById("moreFile")

var br=document.createElement("br")

var input=document.createElement("input")

var button=document.createElement("input")

input.type="file"

input.name="file"

button.type="button"

button.value="-"

button.onclick=function(){

td.removeChild(br)

td.removeChild(input)

td.removeChild(button)

}

td.appendChild(br)

td.appendChild(input)

td.appendChild(button)

}

</script>

</head>

<body>

<form action="/upload/uploadAction.jsp" enctype="multipart/form-data" method="post">

<table>

<tr>

<td>多文件上传</td>

<td></td>

</tr>

<tr>

<td>文件:</td>

<td id="moreFile"><input name="file1" type="file" /><input type="button" value=" + " onclick="addMore()"/></td>

</tr>

<tr>

<td><input type="submit" value="开始上传" /></td>

<td></td>

</tr>

</table>

</form>

</body>

</html>

jsp处理请求页面代码:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<%@page import="org.apache.commons.fileupload.FileUpload"%>

<%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>

<%@page import="java.io.File"%>

<%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>

<%@page import="org.apache.commons.fileupload.FileItem"%>

<%@page import="java.io.FileOutputStream"%>

<%@page import="java.io.BufferedReader"%>

<%@page import="java.io.InputStreamReader"%>

<%@page import="org.apache.commons.fileupload.FileUploadException"%>

<%

//设定请求字符集,防止中文文件名乱码

request.setCharacterEncoding("UTF-8")

//错误或异常提示信息

String errorMsg=""

String strFileName = ""

String path = request.getRealPath("/") + File.separator + "upload/"//上传文件的路径

//判断form是否是multpart/form-data

if(FileUpload.isMultipartContent(request)){

DiskFileItemFactory factory = new DiskFileItemFactory()

// 设置上传工厂的限制

factory.setSizeThreshold(1024 * 1024 * 20)

//new File(request.getRealPath("/")可以具体执行路径

factory.setRepository(new File(path))

// 创建一个上传文件的ServletFileUpload对象

ServletFileUpload upload = new ServletFileUpload(factory)

// 设置最大的上传限制,-1表示无限制

upload.setSizeMax(1024 * 1024 * 20)

// 处理HTTP请求,items是所有的表单项

try {

List<FileItem>items = upload.parseRequest(request)

if(null==items){

errorMsg = "未上传文件,请选择..."

}else{

for(FileItem fi : items){

//判断提交表单元素,是否是上传组件(type=file)

if(fi.isFormField()){

errorMsg = "上传的不是文件类型"

}else{

// 取得文件类型

String fileName = fi.getName()

if(fileName!=null &&!"".equals(fileName)&&fileName.length()>0)

{

strFileName = fileName.substring(fileName.lastIndexOf("\\"),fileName.length())

FileOutputStream fos = new FileOutputStream(path + strFileName)

if (fi.isInMemory()) {

fos.write(fi.get())

} else {

BufferedReader is = new BufferedReader(

new InputStreamReader(fi.getInputStream()))

String str = null

while ((str += is.readLine()) != null) {

byte[] buffer = str.getBytes("ISO-8859-1")

fos.write(buffer)

}

is.close()

}

fos.close()

}

}

}

errorMsg="文件上传成功"

}

} catch (FileUploadException e) {

errorMsg = "文件上传发生错误"+e.getMessage()

e.printStackTrace()

}

}else{

errorMsg = "提交的表单属性设置不正确,不是上传文件的表单"

}

request.setAttribute("msg", errorMsg)

request.getRequestDispatcher("/result.jsp").forward(request, response)

%>

处理结果页面:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head>

<title>文件上传结果</title>

<meta http-equiv="pragma" content="no-cache">

<meta http-equiv="cache-control" content="no-cache">

<meta http-equiv="expires" content="0">

<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

<meta http-equiv="description" content="This is my page">

<!--

<link rel="stylesheet" type="text/css" href="styles.css">

-->

</head>

<body>

上传结果:${msg }

</body>

</html>

先把文件读取到内存,再以二进制格式保持到数据库中的大字段中(clob或clob)。

写大对象。

Java code

public static void main(String[] args) {

// TODO Auto-generated method stub

Connection conn = null

Statement stat = null

ResultSet rs = null

OutputStream os = null

FileInputStream fis = null

int bs = 0

try {

Class.forName("oracle.jdbc.driver.OracleDriver")

conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:oraDB","bigfou","---")

conn.setAutoCommit(false)

stat = conn.createStatement()

stat.executeUpdate("insert into t_video(id,video) values(1,empty_blob())")

rs = stat.executeQuery("select video from t_video where id = 1")

rs.next()

oracle.sql.BLOB blo = (oracle.sql.BLOB)rs.getBlob(1)

os = blo.getBinaryOutputStream()

bs = blo.getBufferSize()

fis = new FileInputStream("D:\\Temp\\MPlayer-CVS-20040808-K&K\\mplayer.exe")

byte[] buf = new byte[bs]

int length = 0

while(true)

{

length = fis.read(buf)

if(length == -1) break

os.write(buf,0,length)

}

os.close()

os = null

fis.close()

fis = null

conn.commit()

conn.setAutoCommit(true)

conn.close()

} catch(Exception ex) {

ex.printStackTrace()

}

}

读大对象

Java code

InputStream is = null

FileOutputStream fos = null

byte[] buf = null

int bs = 0

try {

Class.forName("oracle.jdbc.driver.OracleDriver")

conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:oraDB","bigfou","-")

conn.setAutoCommit(false)

stat = conn.createStatement()

rs = stat.executeQuery("select video from t_video where id = 1")

rs.next()

oracle.sql.BLOB blo = (oracle.sql.BLOB)rs.getBlob(1)

bs = blo.getBufferSize()

buf = new byte[bs]

int length = 0

is = blo.getBinaryStream()

fos = new FileOutputStream("d:\\test.exe")

while(true) {

length = is.read(buf)

if(length == -1) break

fos.write(buf,0,length)

}

fos.close()

fos = null

is.close()

is = null

conn.commit()

conn.setAutoCommit(true)

conn.close()

...


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/tougao/12063914.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-20
下一篇 2023-05-20

发表评论

登录后才能评论

评论列表(0条)

保存