Using Common-fileupload to implement file upload

Source: Internet
Author: User

File upload is a very common function of the site, directly using the servlet to get uploaded files to parse request parameters, more trouble, so the general choice to use

Apache Open source Tools, common-fileupload. This jar pack can be found on the Apache web side, or in the Lib folder of struts,

The ability to upload struts is based on this implementation.

Common-fileupload is dependent on the Common-io package, so it is also necessary to download the package. Then import to your project path below.

Use the following code

Package oop.hg.ytu.servlet;
Import Java.io.File;
Import java.io.IOException;
Import Java.io.InputStream;

Import java.util.List;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;

Import Javax.servlet.http.HttpServletResponse;

Import Oop.hu.ytu.dao.UploadDomain;
Import Org.apache.commons.fileupload.FileItem;
Import Org.apache.commons.fileupload.disk.DiskFileItemFactory;

Import Org.apache.commons.fileupload.servlet.ServletFileUpload;

	public class Upload extends HttpServlet {/** * processing user upload request * * Private static final long serialversionuid = 1L;	public void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {//
		String describe = Request.getparameter ("describe");
		Diskfileitemfactory factory = new Diskfileitemfactory (); @SuppressWarnings ("deprecation") String Path = Request.getrealpath ("/upload");/set disk buffer path Factory.setrepository (new F Ile (Path));
		Factory.setsizethreshold (1024*1024);/set Create buffer size servletfileupload upload = new Servletfileupload (factory); Upload.setsizemax (-1);//Set upload file limit size,-1 No Limit try {@SuppressWarnings ("unchecked") list<fileitem> List = UPLOAD.P
			Arserequest (Request);
			String va = null;
				for (Fileitem item:list) {//String name = Item.getfieldname ();
				if (Item.isformfield ()) {//To determine whether the file stream va = item.getstring ("UTF-8");
			System.out.println (name+ "=" +va);
				Request.setattribute (name, value);
					}else{String value = Item.getname ()//will pass the full path name int start = Value.lastindexof ("\");
			String fileName = value.substring (start+1);
					Request.setattribute (name, fileName);
					InputStream in = Item.getinputstream ();
					Uploaddomain dao = new Uploaddomain ();
					Item.write (New File (Realpath,filename));
					int index = Filename.lastindexof (".");
					String realfilename = filename.substring (0,index);
					String type = filename.substring (index+1); DAo.insert (in, Realfilename,type,va);//Put into the database}} catch (Exception e) {e.printstacktrace (); } public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, Ioexceptio

	n {doget (request, response);
 }

}
Here you will decide whether to upload the stream or the parameters in the form, such as text box submission information, and then insert them into the database. Database insert

The code is as follows

Package Oop.hu.ytu.dao;
Import Java.io.InputStream;
Import java.sql.Connection;
Import java.sql.PreparedStatement;

Import Java.sql.ResultSet;

Import Oop.hg.ytu.utils.JdbcUtils; /** * provides file upload support * @author Administrator */public class Uploaddomain {/** * will upload files into the database/public void Inse RT (InputStream in, String fileName, String type,string describe) throws exception{//writes a picture to the database Connection =  
        Null  
        PreparedStatement PS = null;  
        ResultSet rs = null;
        System.out.println (describe);
            try {//2. Establish Connection conn = Jdbcutils.getconnection ();  
            3. Create statement String sql = INSERT INTO fileupload (file,filename,type,des) values (?,?,?,?);  
            PS = conn.preparestatement (SQL);
            Ps.setblob (1, in);
            Ps.setstring (2, fileName);
            Ps.setstring (3, type);
            Ps.setstring (4, describe);  
  
    4. Execution statement ps.executeupdate ();        In.close ();  
        Finally {Jdbcutils.free (RS, PS, conn);
 }  
    }  
}

You may experience a database default asking price size limit, and you need to change the following configuration below the My.ini under the MySQL installation directory.

[Mysqld]
max_allowed_packet=64m

That's it. Of course, note the encoding format. Upload files to fix. And there's just one of my column names set to describe, the result and MySQL reserved word flushes

Sudden, appear cannot insert information phenomenon, must pay attention to later.

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.