jsp完整图片上传
数据库设计如图: DBConn2.java
package com.db;
import java.sql.Connection; import java.sql.DriverManager;
public class DBConn2 {
String url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=test";
String user="sa";
String pwd="123456";
Connection conn=null;
public Connection get()
{
try {
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance();
conn=DriverManager.getConnection(url,user,pwd);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
}
load.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %>
<title>My JSP 'load.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">
-->
fileupload.jsp
<%@ page language="java" import="java.util.,com.db." pageEncoding="utf-8"%> <%@ page import="java.sql.*" %> <%@page import="org.apache.commons.fileupload.disk.DiskFileItem"%> <%@page import="org.apache.commons.fileupload.DiskFileUpload"%> <%@page import="org.apache.commons.fileupload.FileItem"%> <%@page import="java.io.InputStream"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %>
<title>My JSP 'fileupload.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">
-->
DiskFileUpload fu=new DiskFileUpload();
fu.setHeaderEncoding("utf-8");
fu.setSizeMax(1024*1024*20);
fu.setSizeThreshold(4096);//设置缓冲区4k
fu.setRepositoryPath("c:\\uploade");
List file=fu.parseRequest(request);
Iterator it=file.iterator();
while(it.hasNext()){
FileItem fi=(FileItem)it.next();
if(!fi.isFormField()){
String file1=fi.getName();
String filename=file1.substring(file1.lastIndexOf("\\")+1);
String filecontent=fi.getContentType();
int filesize=(int)fi.getSize();
out.write("文件名"+filename+"<br>");
out.write("文件类型:"+filecontent+"<br>");
out.write("文件大小:"+filesize+"<br>");
ps=conn.prepareStatement(sql);
InputStream is=fi.getInputStream();
System.out.println(filesize);
ps.setString(1,filename);
ps.setBinaryStream(2,is,filesize);
ps.executeUpdate();
is.close();
out.println("文件上传成功!!!");
}
}
}catch(Exception e){
e.printStackTrace();
}finally{
ps.close();
conn.close();
}
%>