Java uses the servlet implementation file to upload to the database and download files from the database __java

Source: Internet
Author: User
Tags create directory dateformat getmessage stub uuid

First, the front desk

1. Upload page

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "
    pageencoding=" UTF-8 "%>
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >
2, download the principle of the page ditto

Second, upload

Package mainservlet;
Import Java.io.File;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.OutputStream;
Import Java.text.DateFormat;
Import Java.text.SimpleDateFormat;
Import Java.util.Calendar;
Import Java.util.Date;
Import java.util.List;

Import Java.util.UUID;
Import javax.servlet.ServletException;
Import Javax.servlet.annotation.WebServlet;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;

Import Javax.servlet.http.HttpServletResponse;
Import Org.apache.commons.fileupload.FileItem;
Import Org.apache.commons.fileupload.FileUploadBase;
Import org.apache.commons.fileupload.FileUploadException;
Import Org.apache.commons.fileupload.ProgressListener;
Import Org.apache.commons.fileupload.disk.DiskFileItemFactory;

Import Org.apache.commons.fileupload.servlet.ServletFileUpload;
Import Bean.fliedao;
Import Bean.imgdao;
Import Bean.tb_flie;

Import bean.tb_img; /** * Servlet Implementation class upLoadhandleservlet */@WebServlet (name= "Uploadhandleservlet", urlpatterns= "/uploadhandleservlet") public class
	 Uploadhandleservlet extends HttpServlet {private static final long serialversionuid = 1L;
    Message prompts//private String massage= "";
        /** * @see httpservlet#httpservlet () * * * Public uploadhandleservlet () {super (); TODO auto-generated Constructor stub}/** * @see httpservlet#doget (httpservletrequest request, HTTPSERVLETRESP Onse response) */protected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexceptio
		N, IOException {//The temporary files generated during upload are saved directory String Temppath=this.getservletcontext (). Getrealpath ("/web-inf/temp"); /** * The two ways to get the saved directory of uploaded files * Method 1 directory generation in the Tomcat directory, once Tomcat clears the project, this file disappears, not considered * 1, String Savepath = This.getservletcontext
		 (). Getrealpath ("/web-inf/upload"); * Method 2 Attfilepath bit webxml the path name configured inside, this directory is a fixed hard disk directory, will not disappear because the project is removed, stable and reliable * 2, String Savepath = This.getservletcontext (). Getinitparameter ("Attfilepath ");
		////Get the saved directory of uploaded files//string savepath = This.getservletcontext (). Getrealpath ("/web-inf/upload");
		Get the Save directory for uploaded files String savepath = This.getservletcontext (). Getinitparameter ("Attfilepath");
		File Tmpfile=new file (TempPath);
		If the temporary file does not exist, create a temporary directory e if (!tmpfile.exists ()) {Tmpfile.mkdir ();
        } String message = "";
		try{//Create a diskfileitemfactory factory diskfileitemfactory factory=new diskfileitemfactory ();
		Sets the size of the buffer to 100KB, if not specified, then the buffer size defaults to 10KB factory.setsizethreshold (1024*100);
		Set the Save directory for the temporary files generated when uploading factory.setrepository (tmpfile);
        Create a file upload parser servletfileupload upload = new Servletfileupload (factory);  Listening for file upload Progress Upload.setprogresslistener (new Progresslistener () {public void update long pbytesread, long
            pcontentlength, int arg2) {System.out.println ("File size: + Pcontentlength +", currently processed: "+ pbytesread);"
        
        }
        });
Set the maximum size of a single file to upload, which is currently set to 1024*1024 Byte, which is 1MB        Upload.setfilesizemax (1024*1024);
        Set the maximum number of uploaded files, maximum = The maximum size of multiple files uploaded at the same time, currently set to 10MB Upload.setsizemax (1024*1024*10); 4, using the Servletfileupload parser to parse the upload data, the result returned is a list<fileitem> set, each fileitem corresponding to a form of the input items List<fileitem
        > list = upload.parserequest (request); for (Fileitem item:list) {//If the data in Fileitem is encapsulated by a normal input item if (Item.isformfield ()) {Strin
                G name = Item.getfieldname ();
                Solve the Chinese garbled problem of the data of the normal input item String value = item.getstring ("UTF-8");
                Value = new String (value.getbytes ("iso8859-1"), "UTF-8");
            SYSTEM.OUT.PRINTLN (name + "=" + value);
                }else{//Get uploaded file name, String filename = Item.getname ();
                SYSTEM.OUT.PRINTLN (filename);
                if (Filename==null | | Filename.trim (). Equals ("")) {continue; //Resolve the Chinese garbled upload of the uploaded filename.Setheaderencoding ("UTF-8"); Note: Different browsers submit the file name is not the same, some browsers submit the file name is a path, such as: C:\a\b\1.txt, and some just simple file name, such as: 1.txt//Processing get the uploaded file filename of the path section, only retain the text
                Part filename = filename.substring (filename.lastindexof ("\") +1); /** * Save uploaded files to database * @author Baicai * Time upload * filen
    		    AME filename * Savepath File path * * */date Date=new date ();
    			DateFormat format=new SimpleDateFormat ("Yyyy-mm-dd hh:mm");
            	String Time=format.format (date);
            	Imgdao imgdao=new Imgdao ();
            	Tb_img tb_img=new tb_img (filename,savepath,time);
            	
                Imgdao.upimg (TB_IMG); Get upload file extension String fileextname = filename.substring (Filename.lastindexof (".")
                +1);
                If you need to limit the file type of upload, you can use the file extension to determine whether the file type uploaded is legitimate System.out.println ("uploaded file extension is:" +fileextname); Get iteThe input stream of the uploaded file in M is inputstream in = Item.getinputstream ();
                Get file saved name String savefilename = makefilename (filename);
                Get File Save directory String Realsavepath = Makepath (Savefilename, Savepath);
                Create a file output stream FileOutputStream out = new FileOutputStream (Realsavepath + "\" + savefilename);
                Create a buffer byte buffer[] = new byte[1024];
                Determine if the data in the input stream has been read out of the identity int len = 0;
                    The loop reads the input stream into the buffer, (len=in.read (buffer)) >0 indicates that there is also a data while (Len=in.read (buffer) >0) {
                Writes the data of the buffer to the specified directory (Savepath + "\" + filename) using the FileOutputStream output stream out.write (buffer, 0, Len);
                //Close the input stream in.close ();
                Turn off the output stream out.close ();
                Deletes the temporary files generated when processing file uploads//item.delete (); Response.getWriter (). println ("<script type= ' Text/javascript ' >alert" (' upload failed.
            ') </script> ");
	        A catch (Fileuploadbase.filesizelimitexceededexception e) {e.printstacktrace ()); Request.setattribute ("Message", "Single file exceeds maximum value ...")
	        ");
	        Request.getrequestdispatcher ("/message.jsp"). Forward (request, response);
	    Return
	        }catch (fileuploadbase.sizelimitexceededexception e) {e.printstacktrace (); Response.getwriter (). println ("<script type= ' Text/javascript ' >alert" (' The total size of the uploaded file exceeds the maximum value of the limit ...).
	        ') </script> ");
	    Return }catch (Exception e) {response.getwriter (). println (' <script type= ' text/javascript ' >alert ' (' upload failed.
	        ') </script> ");
	    E.printstacktrace (); }/** * @Method: Makefilename * @Description: Generate the file name of the uploaded file, the filename is: uuid+ "_" + the original name of the file * @param the original name of the filename file
* @return Uuid+ "_" + the original name of the file */private string Makefilename (string filename) {//2.jpg	        To prevent file overwrite, create a unique filename for uploading files return Uuid.randomuuid (). toString () + "_" + filename; /** * To prevent the occurrence of too many files under a directory, use the hash algorithm to break storage * @Method: Makepath * @Description: * * @param  filename filename, to generate storage directory based on filename * @param savepath file storage path * @return New storage directory/private string Makepath (string		 
	 		Filename,string Savepath) {//Calendar date=calendar.getinstance () with date to get filename; 
	 		SimpleDateFormat format1=new SimpleDateFormat ("Yyyy-mm-dd");
	 		String Name=format1.format (Date.gettime ());  String dir = savepath + "\" + name;
	 		Upload\2\3 upload\3\5 file File=new file (dir);
	        If the directory does not exist if (!file.exists ()) {///Create directory File.mkdirs ();
	    } return dir; /** * @see Httpservlet#dopost (httpservletrequest request, httpservletresponse response) * * protected void DoPost (H Ttpservletrequest request, HttpServletResponse response) throws Servletexception, Ioexception {//TODO auto-generated Method stub doget (request, response);
 }

}

Third, download

Package mainservlet;
Import Java.io.File;
Import Java.io.FileInputStream;
Import java.io.IOException;
Import Java.io.OutputStream;
Import Java.net.URLEncoder;
Import Java.text.SimpleDateFormat;

Import Java.util.Calendar;
Import javax.servlet.ServletException;
Import Javax.servlet.annotation.WebServlet;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;

Import Javax.servlet.http.HttpServletResponse; /** * Servlet Implementation class Imgdown/@WebServlet (urlpatterns= "/imgdown", Name= "Imgdown") public class Imgdown ex
       
    Tends HttpServlet {private static final long serialversionuid = 1L;
        * * @see Httpservlet#httpservlet () * * * ()/public Imgdown () {super (); TODO auto-generated constructor stub} protected void Doget (HttpServletRequest request, HttpServletResponse Respo NSE) throws Servletexception, IOException {//get the filename to download String filename = request.getparameter ("Fliename")
        ; Filename = new String (filename.getbytes ("iso8859-1"), "UTF-8");
        Uploaded files are stored in subdirectories under the Attfilepath (d:/code) directory String Savepath = Request.getparameter ("Fliepath");
               Locate the file's directory by file name String Path = Findfilesavepathbyfilename (Filename,savepath);
        Get the file that you want to download = filename = new file (path + "\" + fileName);
        	If the file does not exist if (!file.exists ()) {request.setcharacterencoding ("utf-8"); Response.getwriter (). println ("<script type= ' text/javascript ' >alert (') The resources you are downloading are deleted.
        ') </script> ");
        //process filename String realname = filename.substring (Filename.indexof ("_") +1); Set the response header to control the browser to download the file Response.setheader ("Content-disposition", "attachment;filename=" + urlencoder.encode (realname,
        "UTF-8"));
        Read the file to be downloaded, save to the file input stream FileInputStream in = new FileInputStream (path + "\" + fileName);
        Create output stream OutputStream out = Response.getoutputstream (); Create buffer byte buffer[]= new byte[1024];
        int len = 0; Loops read the contents of the input stream into the buffer while (len=in.read (buffer) >0) {//output buffer contents to the browser to implement the file download Out.write (BU
        Ffer, 0, Len);
        //close file Input stream in.close ();
    Turn off the output stream out.close (); * * * @Method: Findfilesavepathbyfilename * @Description: File root directory by file name and storage to find the path to the file to download * @param file Name to download the filename * @param saverootpath upload file to save the root directory, that is, the/web-inf/upload directory * @return The storage directory of the files to download */public String Findfilesavepathbyfilename (String filename,string saverootpath) {//Calendar date=calendar.getinstance with date file name (		 
 		); 
 		SimpleDateFormat format1=new SimpleDateFormat ("Yyyy-mm-dd");
 		String Name=format1.format (Date.gettime ());
 		String dir = saverootpath + "\" + name;
 		File File=new file (dir);
        If the directory does not exist if (!file.exists ()) {///Create directory File.mkdirs ();
    } return dir; } public void DoPost (httpservletrequestRequest, HttpServletResponse response) throws Servletexception, IOException {doget (request, response)
    ; }
}
Database section

1. Entity

Package Bean;

public class Tb_img {
	private int id;
	Private String fliename;
	Private String Fliepath;
	private String date;
	public int getId () {return
		ID;
	}
	public void setId (int id) {
		this.id = ID;
	}
	Public String Getfliename () {return
		fliename;
	}
	public void Setfliename (String fliename) {
		this.fliename = fliename;
	}
	Public String Getfliepath () {return
		fliepath;
	}
	public void Setfliepath (String fliepath) {
		this.fliepath = Fliepath;
	}
	public void setdate (String date) {
		this.date = date;
	}
	Public String Getdat () {return
		date;
	}
	Public tb_img () {} public
	tb_img (int id,string fliename,string fliepath,string date) {
		this.id=id;
		This.fliename=fliename;
		This.fliepath=fliepath;
		this.date=date;
	}
	Public tb_img (String fliename,string fliepath,string date) {
		this.fliename=fliename;
		This.fliepath=fliepath;
		This.date=date
	}
}

2, Data layer

Package Bean;
Import java.sql.Connection;
Import java.sql.PreparedStatement;
Import Java.sql.ResultSet;
Import java.sql.SQLException;
Import java.util.ArrayList;

Import java.util.List;

Import Sqldb.sqldb;
	public class Imgdao {private Connection conn=sqldb.getconnection ();
	Tb_img Tb_img=null;
	List<tb_img> Tb_imgs=null; /** * Upload file picture */public void upimg (Tb_img tb_img) throws sqlexception{String sql= ' insert into IMG (Fliename,fliepa
		Th,date) VALUES (?,?,?) ";
		PreparedStatement ptmt=conn.preparestatement (SQL);
		Ptmt.setstring (1, Tb_img.getfliename ());
		Ptmt.setstring (2, Tb_img.getfliepath ());
		Ptmt.setstring (3, Tb_img.getdat ());
	Ptmt.executeupdate ();
		/** * Get ALL data */public list<tb_img> allimg () throws sqlexception{tb_imgs=new arraylist<> ();
		String sql= "SELECT * from IMG";
		PreparedStatement ptmt=conn.preparestatement (SQL);
		ResultSet Rs=ptmt.executequery ();
			while (Rs.next ()) {tb_img=new tb_img ();
	Tb_img.setid (Rs.getint ("id"));		Tb_img.setfliename (rs.getstring ("Fliename"));
			Tb_img.setfliepath (rs.getstring ("Fliepath"));
			Tb_img.setdate (rs.getstring ("date"));
		Tb_imgs.add (TB_IMG);
	return TB_IMGS; /** * Download View file */public list<tb_img> findimg (String context) throws sqlexception{Tb_imgs=new ARRAYLIST&L
		T;> (); String sql= "SELECT * from IMG where fliename like '%" +context + "% ' or fliepath like '%" +context + "% ' or id like '%" +contex
		T + "% '";
		PreparedStatement ptmt=conn.preparestatement (SQL);
		ResultSet Rs=ptmt.executequery ();
			while (Rs.next ()) {tb_img=new tb_img ();
			Tb_img.setid (Rs.getint ("id"));
			Tb_img.setfliename (rs.getstring ("Fliename"));
			Tb_img.setfliepath (rs.getstring ("Fliepath"));
		Tb_imgs.add (TB_IMG);
	return TB_IMGS;
 }
}

3. Linked Database

Package sqldb;
Import java.sql.Connection;
Import Java.sql.DriverManager;
Import java.sql.PreparedStatement;
Import Java.sql.ResultSet;

Import java.sql.SQLException;
	public class Sqldb {private static final String driver= "Com.microsoft.sqlserver.jdbc.SQLServerDriver";
	private static final String URL = "Jdbc:sqlserver://localhost:1433;databasename=text";
	private static final String user= "sa";
	 private static final String password= "123456"; /** * Get connection * @return/public static Connection getconnection () {try {Cl  
            Ass.forname (DRIVER);  
            Connection conn = drivermanager.getconnection (Url,user,password);  
        Return conn; 
        catch (SQLException e) {System.out.println (E.getmessage ());
        catch (ClassNotFoundException e) {System.out.println (E.getmessage ());  
    return null; * * * Close database connection, pay attention to the order of shutdown * * Public VOID Close (ResultSet RS, PreparedStatement PS, Connection conn) {if (rs!=null) {try{  
                Rs.close ();  
            Rs=null;  
            }catch (SQLException e) {e.printstacktrace ();  
                } if (ps!=null) {try{ps.close ();  
            Ps=null;  
            }catch (SQLException e) {e.printstacktrace ();  
                } if (conn!=null) {try{conn.close ();  
            Conn=null;  
            }catch (SQLException e) {e.printstacktrace (); 
 }  
        }  
    }  
}


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.