java上传图片
java servlet上传文件 上传传片 保存到据传 传取文件数
2010-12-29 11:24:00| 分传, java | 传传,servlet request import td public |字号大中小 传传
在传传的传传中~我传可能需要传片、影音等文件直接保存到据传中~然后通传传程方式据传出传将数将数
行使用。例如传出的传片据传示出~传出的传影文件播放出。将数来将来
二传制据直接保存到文件和文件中传出非常的传传。和普通的据传操作差传不大。只是用到部数从数
分流操作。例如各传传入传出流操作。所以深刻理解流操是非常重要的。
在此我借助于一个JSP的传传传例传行传解。此传例保存传传据~其中传传据包含一传片列。此列保数数个
存每名传工的照片。在此照片直接保存到据传中。首先建立传传信息表将数EmployeeInfo~表列非
常的传传
employeeId:传传传;自传增传,~号employeeName:传传姓名~age:传传年传~pic:传传传片;image传型,首先传解信息的保存。先建立一传入界面个index.jsp~其中包含一个元素~用于传用传传传传片文件。
传面代传如下;不做传多传解,,
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%><%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
My JSP 'index.jsp' starting page
传面传求addServlet~传取传入信息~传用并JavaBean传传据保存。数Servlet代传如下,
package com.frank.action;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.frank.rule.*;
public class AddServlet extends HttpServlet {/**
* Constructor of the object.
*/
public AddServlet() {
super();
}
/**
* Destruction of the servlet.
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet.
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server* @param response the response send by the server to the client* @throws ServletException if an error occurred* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String employeeName=request.getParameter("employeeName");
int age=Integer.parseInt(request.getParameter("age"));
String pic=request.getParameter("pic");
EmployeeDAO employeeDAO=new EmployeeDAO();
if(employeeDAO.employeeAdd(employeeName, age, pic))
response.sendRedirect("success.jsp");
else
response.sendRedirect("index.jsp");
}
/**
* The doPost method of the servlet.
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server* @param response the response send by the server to the client
* @throws ServletException if an error occurred* @throws IOException if an error occurred*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
/**
* Initialization of the servlet.
*
* @throws ServletException if an error occurs*/
public void init() throws ServletException {
// Put your code here
}
}
此Servlet只是传传的传取传面传入的据~其中传取的数Pic传用传传传的传片路。传格传~传取文件需要传传传径
传~防止非法传片的传传~传可以根据自己的需要改善。然后个Servlet传用传传传~传取的据通传将数参
数数传入~传行据的增加。其中employeeAdd方法传传据的保存~代传如下,数
public boolean employeeAdd(String employeeName,int age,String pic){
Connection conn=null;
PreparedStatement pstmt=null;
FileInputStream fis=null;
try{
Class.forName("net.sourceforge.jtds.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:jtds:sqlserver://localhost:1433/SampleDB","sa","");
fis=new FileInputStream(pic);
String strSQL="INSERT INTO employeeInfo VALUES(?,?,?)";
pstmt=conn.prepareStatement(strSQL);
pstmt.setString(1, employeeName);
pstmt.setInt(2, age);
pstmt.setBinaryStream(3, fis, fis.available());
if(pstmt.executeUpdate()>0)
return true;
else
return false;
}catch(ClassNotFoundException ex){
ex.printStackTrace();
return false;
}catch(SQLException ex){
ex.printStackTrace();
return false;
}catch(IOException ex){
ex.printStackTrace();
return false;
}finally{
try{
fis.close();
pstmt.close();
conn.close();
}catch(Exception ex){
}
}
}
注意粗部分~用传取的体pic信息;文件路,传建文件传入流传象~增加径pic字段的容通传流传象内
增加。
pstmt.setBinaryStream(3, fis, fis.available());
三分传传,索引~流传象~流传象大小个参数参数
当增加成功传~重定向到success.jsp
运行传果如下,
增加后~传示如下代表成功,
那传如何传传传片据是否保存到了据传中,我传通传再次传索增加的据~传出增加的传片据数数呢数数并
在传面中传示出传行传传。来
首先建立一非常传传的传面个search.jsp~此传面通传文本使用传传入要传索的人传的姓名~传索人传的框基本信息;不传索传片据,~传索的人传据形成数将数JOPO传象~保存到session中~以便传面使用。
JOPO传;EmployeeObj)
package com.frank.obj;
public class EmployeeObj {private int employeeId;private String employeeName;private int age;
public int getEmployeeId() {
return employeeId;
}
public void setEmployeeId(int employeeId) {
this.employeeId = employeeId;
}
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
search.jsp传面代传如下,
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
My JSP 'search.jsp' starting page
通传searchServlet传传基本信息的传索
package com.frank.action;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.frank.obj.EmployeeObj;
import com.frank.rule.EmployeeDAO;
public class SearchServlet extends HttpServlet {/**
* Constructor of the object.
*/
public SearchServlet() {
super();
}
/**
* Destruction of the servlet.
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet.
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server* @param response the response send by the server to the client* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String employeeName=request.getParameter("employeeName");
EmployeeDAO employeeDAO=new EmployeeDAO();
EmployeeObj employeeObj=employeeDAO.getEmployeeByName(employeeName);
HttpSession session=request.getSession();
session.setAttribute("employee", employeeObj);
response.sendRedirect("display.jsp");
}
/**
* The doPost method of the servlet.
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server* @param response the response send by the server to the client* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
/**
* Initialization of the servlet.
*
* @throws ServletException if an error occurs*/
public void init() throws ServletException {
// Put your code here
}
}
此Servlet传用传传传的 getEmployeeByName方法传索人传基本信息~返回EmployeeObj传象~放入并session中~然也可以放入当request中~根据自己的需要改传。传面传索成功后重定向到display.jsp传行信息的传示;稍后传解,
getEmployeeByName方法代传如下,
public EmployeeObj getEmployeeByName(String employeeName){
Connection conn=null;
PreparedStatement pstmt=null;
ResultSet rst=null;
EmployeeObj employeeObj=new EmployeeObj();
try{
Class.forName("net.sourceforge.jtds.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:jtds:sqlserver://localhost:1433/SampleDB","sa","");
String strSQL="SELECT employeeId,employeeName,age FROM EmployeeInfo WHERE
employeeName=?";
pstmt=conn.prepareStatement(strSQL);
pstmt.setString(1, employeeName);
rst=pstmt.executeQuery();
if(rst.next()){
employeeObj.setEmployeeId(rst.getInt("employeeId"));
employeeObj.setEmployeeName(rst.getString("employeeName"));
employeeObj.setAge(rst.getInt("age"));
return employeeObj;
}
return null;
}catch(ClassNotFoundException ex){
ex.printStackTrace();
return null;
}catch(SQLException ex){
ex.printStackTrace();
return null;
}finally{
try{
pstmt.close();
conn.close();
}catch(Exception ex){
}
}
}
display.jsp传传传示传传出的传果信息~代传如下,
<%@ page language="java" import="java.util.*,com.frank.obj.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
My JSP 'display.jsp' starting page
<%
EmployeeObj employeeObj=(EmployeeObj)session.getAttribute("employee");%>
EmployeeId
<%=employeeObj.getEmployeeId() %>
EmployeeName
<%=employeeObj.getEmployeeName() %>
Age
<%=employeeObj.getAge() %>
Pic
代传非常的传传~只是传传的从session 中传取保存的EmployeeObj传象~然后利用jsp表式据成达将数传信息传示到传面上。但是注意粗部分~因传我传需要保存的传片据传出~然后传示成传片。所以体将数
在此我传利用Img元素传示传片~而Src利用displayServlet的行传果传出到客传端~作传传片的传示源运。
displayServlet包含参数employeeId~用定具传示一传工的传片。来决体哪
displayServlet通传Servlet传出流~传取的传片据传送到客传端~代传如下,将数
package com.frank.action;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.frank.rule.EmployeeDAO;
public class DisplayServlet extends HttpServlet {/**
* Constructor of the object.
*/
public DisplayServlet() {
super();
}
/**
* Destruction of the servlet.
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. *
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred* @throws IOException if an error occurred*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("image/gif");
int employeeId=Integer.parseInt(request.getParameter("employeeId"));
EmployeeDAO employeeDAO=new EmployeeDAO();
InputStream is=employeeDAO.getPicById(employeeId);
int size=is.available();
byte[] image=new byte[size];
is.read(image);
ServletOutputStream out=response.getOutputStream();
out.write(image);
}
/**
* Initialization of the servlet. *
* @throws ServletException if an error occurs*/
public void init() throws ServletException {
// Put your code here
}
}
在此~传用传传传的getPicById方法得到传片据的传入流。然后传取的传入流到数写
ServletOutputStream~传传可以在Servlet的传出端使用~即img的src中使用getPicById代传如下,
public InputStream getPicById(int employeeId){
Connection conn=null;
PreparedStatement pstmt=null;
ResultSet rst=null;
InputStream is=null;
try{
Class.forName("net.sourceforge.jtds.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:jtds:sqlserver://localhost:1433/SampleDB","sa","");
String strSQL="SELECT pic FROM EmployeeInfo WHERE employeeId=?";
pstmt=conn.prepareStatement(strSQL);
pstmt.setInt(1, employeeId);
rst=pstmt.executeQuery();
if(rst.next()){
is=rst.getBinaryStream("pic");
return is;
}
return null;
}catch(ClassNotFoundException ex){
ex.printStackTrace();
return null;
}catch(SQLException ex){
ex.printStackTrace();
return null;
}finally{
try{
pstmt.close();
conn.close();
}catch(Exception ex){
}
}
}
注意粗部分体
好了~我传可以通传行传果传行传传~假传我传搜索名传运来称Mike的人传据~那传传传,数
点search按传~行看到传片,运将会
好了~传示出了传索传果~不但包括人传的基本据~保存到据传中的传片据也被传出传示成传片数数数并。代传只是利用jsp传传的传行传~大家可以根据自己的需要传行改传。体
传一你个JSP上传文件到ORACLE成功的例子
====================
upload1.jsp
====================
view plain copy to clipboard print ?
1.//传传上传文件
2. <%@ page contentType= "text/html; charset=gb2312 "%>
3.
4.
5.
6.
7.
8.
23.
24.
25.======================
26.upload.jsp
27.======================
28.//上传文件传理传面
29. <%@ page contentType= "text/html;charset=gb2312 "%>
30. <%@ page language= "java "%>
31. <%@ page import= "java.sql.* " %>
32. <%@ page import= "com.dd.database.DatabaseService "%>
33.
34. <%
35. try
36.{
37. String sessionID=session.getId(); 38. DatabaseService pobjDatabaseService = new DatabaseService(); 39. //传例化上传bean
40. com.jspsmart.upload.SmartUpload mySmartUpload=new
com.jspsmart.upload.SmartUpload();
41. //初始化
42. mySmartUpload.initialize(pageContext); 43. //传置上传的最大传
44. mySmartUpload.setMaxFileSize(500 * 1024*1024);
45. //上传文件
46. mySmartUpload.upload(); 47. //循传取得所有上传的文件
48. for (int i=0;i
50. {
51. //取得上传的文件
52. com.jspsmart.upload.File myFile = mySmartUpload.getFiles().getFile(i); 53. if (!myFile.isMissing()) 54. {
55. //取得文件全名
56. String myFileName=myFile.getFileName(); 57. //取得不传后传的文件名
58. String suffix=myFileName.substring(0,myFileName.lastIndexOf( '. '));
59. //取得后传名
60. String ext= mySmartUpload.getFiles().getFile(0).getFileExt(); 61. if(ext.equals( "exe "))
62. {
63. out.println( "上传文件不能传EXE文件 "); 64. return;
65. }
66. //取得文件的大小
67. int fileSize=myFile.getSize(); 68. //保存路 径
69. String aa=getServletContext().getRealPath( "/ ")+ "upfile\\ "; 70. String trace=aa+myFileName; 71. //取得传的 参数
72. String explain=(String)mySmartUpload.getRequest().getParameter( "text ");
73. String send=(String)mySmartUpload.getRequest().getParameter( "send ");
74. //将文件保存在服传器端
75. myFile.saveAs(trace,com.jspsmart.upload.File.SAVEAS_PHYSICAL);
76.
77. //将数上传的文件保存到据传中
78. //将文件传到流中
79. java.io.File file = new java.io.File(trace); 80. java.io.FileInputStream fis = new java.io.FileInputStream(file);
81. //打传据传 数
82. String mStrSql=null;
83. ResultSet mobjResult=null;
84. PreparedStatement mobjPrestmt=null;
85. mStrSql= "insert into
H_uploadfile(markname,marksize,MarkBody,randomname,sessionid) values (?,?,?,?,?) ";
86. java.util.Random pobjRandom = new java.util.Random(new java.util.Date().getTime());
87. long plogRandom = pobjRandom.nextLong();
88. String mstrRandomName = String.valueOf(plogRandom); 89. //随机名
90. mstrRandomName = mstrRandomName + ". " + ext;
91. mobjPrestmt=pobjDatabaseService.getPreparedStatement(mStrSql);
92. mobjPrestmt.setString(1, suffix); 93. mobjPrestmt.setInt(2, fileSize); 94. mobjPrestmt.setBinaryStream(3,fis,(int)file.length()); 95. mobjPrestmt.setString(4,mstrRandomName); 96. mobjPrestmt.setString(5,sessionID); 97. pobjDatabaseService.setAutoCommit();
98. mobjPrestmt.executeUpdate(); 99. pobjDatabaseService.commit(); 100. response.sendRedirect( "jlwj/uploadwenjian.jsp?id=15 "); 101. }
102. else
103. {
104. out.println(( "上传失传, ").toString()); 105. }
106. }
107.}
108.catch(Exception er)
109.{
110. out.println( " ");
111. out.println(er.getMessage()); 112.}
113.%>
114.======================
115.uploadwenjian.jsp
116.======================
117.//上传成功后跳传到传传传示出当前已上传成功的附件
118.//你要上传的是传片~那传下面传示的地方改传 就行了
119. <%@ page contentType= "text/html; charset=gb2312 "%> 120. <%@ page import= "com.dd.commons.* "%>
121. <%@ page language= "java "%>
122. <%@ page import= "java.sql.* "%>
123. <%@ page import= "java.io.* "%>
124. <%@ page import= "com.dd.database.DatabaseService "%> 125.
126.
127.
128. 129. 无传传文 档
130. 131.
141.
142.