Springmvc file, upload, preview. Store in binary form to database (reprint)

Source: Internet
Author: User
Tags stringbuffer

Springmvc file Upload, download, preview. stored in binary form to the database.
Fields about incoming attachments in the database I wrote 2: a content accessory, a suffix to store files filetype

Upload: You need 2 required jars first:
Commons.io-1.4.0.jar
Commons.fileupload-1.2.0.jar

Write upload interception in Xxx-servlet.xml:
<bean id= "Multipartresolver" class= "Org.springframework.web.multipart.commons.CommonsMultipartResolve" >
<property name= "Maxuploadsize" value= "100000"/>
</bean>


JSP page:
<form method= "POST" action= "Submit Address" name= "frm" enctype= "Multipart/form-data" >
<input type= "file" name= "accessory"/><br>
<input type= "Submit" onclick= "return Checkacc ();" /><br>
</form>
<!--If you need to verify the type of the incoming file, it can be verified by JS, which I verified at the time of submission.
<!--
function Checkacc () {
var postfix = frm.accessory.value.substring (Frm.accessory.value.lastIndexOf (".") +1); A regular expression that obtains the suffix name of the selected upload file
if (postfix!= "") {
if (! ( Postfix = = "JPG" | | Postfix = = "pdf"))
{
Alert (' file type is incorrect, please select. jpg or. pdf file! ‘);
document.getElementById (' accessory '). value= "";
document.getElementById (' accessory '). focus ();
return false;
}
}
}
-

Note: In a previously written file uploaded with a servlet, adding the Enctype= "multipart/form-data" field will result in not getting the value of the other fields in the form, but this problem does not occur in SPRINGMVC.


Java Controller class:
Public Modelandview Addsalestock (httpservletrequest request,httpservletresponse response) throws Exception {
Multiparthttpservletrequest multipartrequest = (multiparthttpservletrequest) request;
Multipartfile file = Multipartrequest.getfile ("accessory");
byte[] Inputdata = null;
String filetype= "";
if (file!=null) {
Inputdata = Inputstream2byte (File.getinputstream ());
String S=file.getoriginalfilename ();
Filetype=s.substring (S.lastindexof (".") +1);
}
The object class (model) of a table in a database, commonly said to be the PO in hibernate
Validregstock Validregstock = new Validregstock ();
Validregstock.setinputdata (Inputdata);
Validregstock.setfiletype (FileType);
try {
To see the service class
This.getbeanofvalidregstockservice (). Addsendregstock (Validregstock);
msg = "added successfully! ";
} catch (Exception e) {
E.printstacktrace ();
msg = "Add failed!" ";
}
return new Modelandview (returning address);
}


Java Service class:
public void Addsendregstock (Validregstock validregstock)
Throws Exception {
To see the DAO class
Regstockdao.add (Validregstock);
}


Java DAO Class:
public void Add (Validregstock validregstock) {
String sql= "INSERT into Z_validregstock (Accessory,filetype) VALUES (?,?)";
Here we use the data connection to deposit the database
Connection Conn=null;
try {
conn = Getjdbctemplate (). Getdatasource (). getconnection ();
PreparedStatement ps=conn.preparestatement (SQL);
Note: The large object type we deposited is bytes[], here to set object
Ps.setobject (1, Validregstock.getinputdata ());
Ps.setstring (2, Validregstock.getfiletype ());
Ps.executeupdate ();
Conn.commit ();
Ps.close ();
Conn.close ();
} catch (SQLException e) {
E.printstacktrace ();
}
}

So you can upload it. It is important to note that:

Some friends will use:
Object[] Params={validregstock.getinputdata ()};
Int[] Datatypes={types.xxx};
Getjdbctemplate (). Update (SQL, params, datatypes);
This method is deposited, where I used types.xxx because I tried types.blob,types.other and so on. And I put bytes[] with hibernate into the java.sql.blob of the deposit words is not good to make. A type mismatch Java.oracle.blob will appear. So please let me know if you can use this method to succeed friends. Thank you

Preview and download almost. The same service, the same DAO, I give the DAO and service first:
Java DAO Class:
Public List Accessorysel (String ID) {
StringBuffer sql=new StringBuffer ("");
Sql.append ("Select Accessory,filetype from Z_validregstock where regstockid= '");
Sql.append (ID);
Sql.append ("'");
Connection Conn=null;
Statement State=null;
ResultSet rs = null;
List list=new ArrayList ();
try {
Conn=getjdbctemplate (). Getdatasource (). getconnection ();
State=conn.createstatement ();
Rs=state.executequery (Sql.tostring ());
if (Rs.next ()) {
This blob is of type Java.sql.Blob.
Blob blob = Rs.getblob ("accessory");
String filetype=rs.getstring ("filetype");
List.add (0, BLOB);
List.add (1,filetype);
}
} catch (SQLException e) {
E.printstacktrace ();
}
return list;
}


Java Service class:
Public List Accessorysel (String ID) {
return Regstockdao.accessorysel (ID);
}



Java Controller class:
Preview:
Public Modelandview Getaccessoryview (httpservletrequest request,httpservletresponse response) throws Exception {
String id=request.getparameter ("id");
List List=this.getbeanofvalidregstockservice (). Accessorysel (ID);
Blob blob= (BLOB) list.get (0);
String filetype= (String) list.get (1);
int length = (int) blob.length ();
byte[] Bimage = new Byte[length];
InputStream is = new Bufferedinputstream (Blob.getbinarystream ());
Is.read (bimage, 0, length);
OutputStream out = Response.getoutputstream ();
Out.write (Bimage);
Out.flush ();
Out.close ();
Is.close ();
return null;
}



Download:
Public Modelandview getaccessorydownload (httpservletrequest request,httpservletresponse response) throws Exception {
The ID of the data that the JSP sent to download the attachment.
String id=request.getparameter ("id");
List List=this.getbeanofvalidregstockservice (). Accessorysel (ID);
Blob blob= (BLOB) list.get (0);
String filetype= (String) list.get (1);
OutputStream fos = Response.getoutputstream ();
InputStream is = new Bufferedinputstream (Blob.getbinarystream ());
If the download is in tabular form, garbled characters may occur. Add the following sentence: (Other garbled situation of their own Baidu under.) )
Response.setheader ("Content-type", "application/vnd.ms-excel");
The statement that pops up the Save box, which can then be filled in with the default name and type
Response.setheader ("Content-disposition", "attachment;filename=accessory." +filetype);
byte[] buffer = new byte[1024];
int size = 0;
while (size = is.read (buffer))! =-1) {
Fos.write (buffer, 0, size);
}
Fos.flush ();
Fos.close ();
return null;
}
}

Springmvc file, upload, preview. Store in binary form to database (reprint)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.