Haha, why should I laugh?
Because I am bored. I don't know what to do on weekends? Mixed up in the forum, a buddy scored 100 points and asked for an example of uploading images to the database.
There should be a lot on the Internet, so I thought I 'd like to make a profit if I want this score (--!). Write it. In the future, whoever needs to change it will become. Now, proceed to the question:
First, I declare that I have not installed any other databases in this book. I just need to install MySQL (because it's a little bit --!), In fact, they are similar.
Database creation:
Database Name: csdn
Table Name: savepicture
Drop table if exists 'savepicture ';
Create Table 'savepicture '(
'Id' int (10) Not null auto_increment,
'Picture' blob not null,
Primary Key ('id ')
) Engine = InnoDB default charset = utf8;
Create a project:
In fact, it is very simple to understand at a glance. Just export all the required packages.
Next we create the upload page:
<% @ Page Language = "Java" pageencoding = "UTF-8" %>
<% @ Taglib prefix = "S" uri = "/Struts-tags" %>
<! Doctype HTML public "-// W3C // dtd html 4.01 transitional // en">
<HTML>
<Head>
<Title> File Upload </title>
<Link href = "<% = request. getcontextpath () %>/CSS/fileupload.css"
Rel = "stylesheet" type = "text/CSS">
</Head>
<Body bgcolor = "# cccccc">
<Div style = "padding-top: 30px; padding-left: 30px">
<Fieldset
Style = "width: 600px; border-color: #000000; padding-left: 10px">
<Legend>
<Font size = "-1" color = "#000000"> <B> upload an image </B> </font>
</Legend>
<Div class = "errordiv">
<S: fielderror/>
<S: actionerror/>
</Div>
<S: Form Action = "fileupload. Action" method = "Post" theme = "simple"
Enctype = "multipart/form-Data">
<Table border = "1" width = "500px">
<Tr>
<TD class = "tabletdcenter">
Image path:
</TD>
<TD class = "tabletdcenter">
<S: file name = "file" cssclass = "fileinput"/>
</TD>
</Tr>
<Tr>
<TD class = "tabletdcenter" colspan = "2">
<S: Submit value = "Submit" cssclass = "button"> </S: Submit>
</TD>
</Tr>
</Table>
</S: Form>
</Fieldset>
</Div>
</Body>
</Html>
It is very simple, it is an upload box and button, nothing else. As for some CSS, it is a little decorative, and I will write it below later!
Let's take a look at the struts2 configuration file:
<? XML version = "1.0" encoding = "UTF-8"?>
<! Doctype struts public
"-// Apache Software Foundation // DTD struts configuration 2.0 // en"
Http://struts.apache.org/dtds/struts-2.0.dtd>
<Struts>
<Constant name = "struts. Custom. i18n. Resources"
Value = "messageresource"/>
<Constant name = "struts. i18n. encoding" value = "UTF-8"/>
<Package name = "default" extends = "struts-Default">
<! -- Upload -->
<Action name = "fileupload"
Class = "org. csdn. Action. fileuploadaction">
<Interceptor-ref name = "defaultstack"/>
<Interceptor-ref name = "fileupload">
<Param name = "allowedtypes">
Image/BMP, image/PNG, image/GIF, image/jpg
</Param>
<Param name = "maximumsize"> 404800 </param>
</Interceptor-ref>
<Result name = "success">/uploadsuccess. jsp </result>
<Result name = "input">/fileupload. jsp </result>
</Action>
<! -- Output display -->
<Action name = "outpicture"
Class = "org. csdn. Action. outpictureaction">
<Result name = "input">/uploadsuccess. jsp </result>
</Action>
</Package>
</Struts>
As for what is in it, you will surely know it by name.
I referenced the messageresource resource file above to Display error messages. For example, the upload type is incorrect, the size is exceeded, and the upload fails.
The following is the content in the resource file.
Struts. Messages. Error. content. type. Not. Allowed = the file you uploaded is not a image
Struts. Messages. Error. file. Too. Large = This picutre is too large
Fileupload. Fail = File Upload is fail
If the two keys are not redefined, the default error message of struts2 is displayed, Which is ugly and messy. So I redefined it.
Then we begin to write the actions for uploading and outputting images, and related class information.
Upload action:
Import java. Io. file;
Import java. util. List;
Import org. csdn. Service. fileuploadservice;
Import org. csdn. VO. picture;
Import com. opensymphony. xwork2.actioncontext;
Import com. opensymphony. xwork2.actionsupport;
/**
* @ Author closewubq
*/
Public class fileuploadaction extends actionsupport {
Private Static final long serialversionuid = 1l;
Private file;
Public file GetFile (){
Return file;
}
Public void setfile (File file ){
This. File = file;
}
/**
* Upload a file
*/
@ Override
Public String execute (){
Fileuploadservice fuservice = new fileuploadservice ();
If (fuservice. fileupload (File )){
List <picture> List = fuservice. findall ();
Actioncontext cxt = actioncontext. getcontext ();
Cxt. Put ("list", list );
Return success;
} Else {
Super. addactionerror (this. gettext ("fileupload. Fail "));
Return input;
}
}
}
It is very simple, because I only use struts2 and spring. Therefore, fileuploadservice is written in hard encoding. ,
Main business category of image uploading
Import java. Io. file;
Import java. Io. fileinputstream;
Import java. Io. inputstream;
Import java. SQL. connection;
Import java. SQL. preparedstatement;
Import java. SQL. resultset;
Import java. util. arraylist;
Import java. util. List;
Import org. csdn. Connection. getconnection;
Import org. csdn. VO. picture;
/**
* @ Author closewubq
*/
Public class fileuploadservice {
/**
* Upload images to the database
* @ Param flie
* @ Return Boolean
* Indicates whether the upload is successful.
*/
Public Boolean fileupload (File flie ){
Fileinputstream in = NULL;
Connection conn = NULL;
Preparedstatement PS = NULL;
Try {
In = new fileinputstream (flie );
String SQL = "insert into savepicture (picture) value (?) ";
Conn = getconnection. getconn ();
If (conn = NULL ){
System. Out. println ("connection is null ");
Return false;
}
PS = conn. preparestatement (SQL );
PS. setbinarystream (1, in, in. Available ());
If (ps.exe cuteupdate ()> 0 ){
Getconnection. Close (Conn, PS, null );
Return true;
} Else {
Getconnection. Close (Conn, PS, null );
Return false;
}
} Catch (exception e ){
System. Out. println (E. getmessage ());
Getconnection. Close (Conn, PS, null );
Return false;
}
}
/**
* Retrieve all images
* @ Return list
* Returns all image records.
*/
Public list <picture> findall (){
List <picture> List = new arraylist <picture> ();
Picture PIC = NULL;
Connection conn = NULL;
Preparedstatement PS = NULL;
Resultset rs = NULL;
Try {
String SQL = "select ID from savepicture ";
Conn = getconnection. getconn ();
If (conn = NULL ){
System. Out. println ("connection is null ");
Return NULL;
}
PS = conn. preparestatement (SQL );
Rs = ps.exe cutequery ();
While (Rs. Next ()){
PIC = new picture ();
PIC. setid (Rs. getint ("ID "));
List. Add (PIC );
}
Getconnection. Close (Conn, PS, RS );
Return list;
} Catch (exception e ){
E. printstacktrace ();
Getconnection. Close (Conn, PS, RS );
Return NULL;
}
}
/**
* Retrieving stream Objects Based on Image IDS
* @ Param ID
* @ Return inputstream
*/
Public inputstream getpicbyid (int id ){
Connection conn = NULL;
Preparedstatement PS = NULL;
Resultset rs = NULL;
Inputstream is = NULL;
Try {
String SQL = "select picture from savepicture where id =? ";
Conn = getconnection. getconn ();
PS = conn. preparestatement (SQL );
PS. setint (1, ID );
Rs = ps.exe cutequery ();
If (Rs. Next ()){
Is = Rs. getbinarystream ("picture ");
Getconnection. Close (Conn, PS, RS );
Return is;
}
Getconnection. Close (Conn, PS, RS );
Return NULL;
} Catch (exception ex ){
Ex. printstacktrace ();
Getconnection. Close (Conn, PS, RS );
Return NULL;
}
}
}
Write a JDBC link acquisition class.
Import java. SQL. connection;
Import java. SQL. drivermanager;
Import java. SQL. preparedstatement;
Import java. SQL. resultset;
Import java. SQL. sqlexception;
/**
* Getting database links
* @ Author closewubq
*/
Public class getconnection {
/**
* Getting database connections
* @ Return connection
* Return to database connection
*/
Public static connection getconn (){
Try {
Class. forname ("com. MySQL. JDBC. Driver"). newinstance ();
String url = "JDBC: mysql: // localhost/csdn? User = root & Password = ";
Connection connection = drivermanager. getconnection (URL );
Return connection;
} Catch (exception e ){
E. printstacktrace ();
Return NULL;
}
}
/**
* Close the connection and release resources.
* @ Param Conn
* @ Param rs
* @ Param St
*/
Public static void close (connection Conn, preparedstatement ps, resultset RS ){
If (RS! = NULL)
Try {
Rs. Close ();
} Catch (sqlexception e ){
E. printstacktrace ();
}
If (PS! = NULL)
Try {
PS. Close ();
} Catch (sqlexception e ){
E. printstacktrace ();
}
If (Conn! = NULL)
Try {
Conn. Close ();
} Catch (sqlexception e ){
E. printstacktrace ();
}
}
}
There are also VO for saving Image Information
Public class picture {
Private int ID;
Public int GETID (){
Return ID;
}
Public void setid (int id ){
This. ID = ID;
}
}
Action for outputting Image Information
Import java. Io. inputstream;
Import javax. servlet. servletoutputstream;
Import javax. servlet. http. httpservletrequest;
Import javax. servlet. http. httpservletresponse;
Import org. Apache. struts2.servletactioncontext;
Import org. csdn. Service. fileuploadservice;
Import com. opensymphony. xwork2.actionsupport;
/**
* Image output
* @ Author closewubq
*
*/
Public class outpictureaction extends actionsupport {
Private Static final long serialversionuid = 1l;
@ Override
Public String execute () throws exception {
Httpservletrequest request = servletactioncontext. getrequest ();
Int id = integer. parseint (request. getparameter ("ID "));
Fileuploadservice service = new fileuploadservice ();
Inputstream in = service. getpicbyid (ID );
Httpservletresponse response = servletactioncontext. getresponse ();
Response. setcontenttype ("image/GIF ");
Int size = in. Available ();
Byte [] image = new byte [size];
In. Read (image );
Servletoutputstream out = response. getoutputstream ();
Out. Write (image );
Return NULL;
}
}
Over, over. Let's start and see the effect:
Hey, let's upload some of my handsome photos. Haha success ......