File upload download-servlet API implementation

Source: Internet
Author: User
Tags uuid

The Servlet API implements a file upload to download the required jar package:

Uploadservlet.java

 PackageCom.ymw.web.servlet;ImportJava.io.File;ImportJava.io.FileOutputStream;ImportJava.io.IOException;ImportJava.io.InputStream;ImportJava.util.List;ImportJava.util.UUID;ImportJavax.servlet.ServletException;ImportJavax.servlet.http.HttpServlet;ImportJavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;ImportOrg.apache.commons.fileupload.FileItem;ImportOrg.apache.commons.fileupload.FileUploadBase;ImportOrg.apache.commons.fileupload.ProgressListener;ImportOrg.apache.commons.fileupload.disk.DiskFileItemFactory;ImportOrg.apache.commons.fileupload.servlet.ServletFileUpload;/** * @ClassName: Uploadhandleservlet * @Description: TODO * @author: LMB * */ Public  class uploadhandleservlet extends httpservlet {    Private Static Final LongSerialversionuid =1L Public void Doget(HttpServletRequest request, httpservletresponse response)throwsServletexception, IOException {//Get uploaded files to save directory, the uploaded files in the Web-inf directory, not allow direct access to the outside world, to ensure the security of uploading filesString Savepath = This. Getservletcontext (). Getrealpath ("/images");//Temporary files generated at upload save directoryString TempPath = This. Getservletcontext (). Getrealpath ("/web-inf/temp"); File tmpfile =NewFile (TempPath);if(!tmpfile.exists ()) {//Create temp directoryTmpfile.mkdir (); }//Message promptString message ="";Try{//Use the Apache File Upload component to process file upload steps:            ///1, create a diskfileitemfactory factoryDiskfileitemfactory factory =NewDiskfileitemfactory ();//Set the size of the factory buffer, and when the uploaded file size exceeds the size of the buffer, a temporary file is generated to be stored in the specified temporary directory. Factory.setsizethreshold (1024x768* -);//Set buffer size to 100KB, if not specified, the buffer size defaults to 10KB            //Set the Save directory for temporary files generated when uploadingFactory.setrepository (tmpfile);///2, create a file upload parserServletfileupload upload =NewServletfileupload (Factory);//Monitor file upload ProgressUpload.setprogresslistener (NewProgresslistener () { Public void Update(LongPbytesread,LongPcontentlength,intARG2) {System.out.println ("File size is:"+ Pcontentlength +", currently processed:"+ Pbytesread);/** * File size: 14608, currently processed: 4096 file size: 14608, currently processed: 7367 * File Size: 14608, currently processed: 11419 File size: 14608, currently processed: 14608 */}            });//Solve the Chinese characters of uploading file nameUpload.setheaderencoding ("UTF-8");//3, determine whether the submitted data is the upload form data            if(! Servletfileupload.ismultipartcontent (Request)) {//Get data in the traditional way                return; }//Set the maximum size of the uploaded single file, currently set to 1024*1024 bytes, which is 1MBUpload.setfilesizemax (1024x768*1024x768);//Set the maximum number of uploaded files, max = The sum of the maximum values of the size of multiple files uploaded simultaneously, currently set to 10MBUpload.setsizemax (1024x768*1024x768*Ten);///4, using the Servletfileupload parser to parse the upload data, the result of the parse is a list<fileitem> collection, each fileitem corresponding to the input of a form formlist<fileitem> list = upload.parserequest (request); for(Fileitem item:list) {//If the data for the normal input is encapsulated in the Fileitem                if(Item.isformfield ()) {String name = Item.getfieldname ();//Solve the problem of Chinese garbled data of ordinary input itemsString value = item.getstring ("UTF-8");//value = new String (value.getbytes ("iso8859-1"), "UTF-8");SYSTEM.OUT.PRINTLN (name +"="+ value); }Else{//If the upload file is encapsulated in Fileitem                        //Get the uploaded file name,String filename = Item.getname ();                    SYSTEM.OUT.PRINTLN (filename); Request.setattribute ("FileName", filename);if(FileName = =NULL|| Filename.trim (). Equals ("")) {Continue; }//Note: The file names submitted by different browsers are not the same, and some browsers submit filenames with paths, such as:                    //C:\a\b\1.txt, and some are simply file names, such as: 1.txt                    //Process the path portion of the filename of the uploaded file to be retrieved, leaving only the file name sectionfilename = filename. substring (filename.lastindexof ("\\") +1);//Get the extension of the uploaded fileString fileextname = filename.substring (filename. lastIndexOf (".") +1);//If you need to limit the types of files uploaded, you can determine whether the uploaded file type is valid through the file's extensionSystem.out.println ("The file name extension for the upload is:"+ Fileextname);//Gets the input stream of the uploaded file in itemInputStream in = Item.getinputstream ();//Get the name of the file savedString savefilename = makefilename (filename);//Get the File save directoryString Realsavepath = Makepath (Savefilename, Savepath);//Create a file output streamFileOutputStream out =NewFileOutputStream (Realsavepath +"\\"+ Savefilename);//Create a buffer                    byteBuffer[] =New byte[1024x768];//Determine if the data in the input stream has been read out of the identity                    intLen =0;The //loop reads the input stream into the buffer, (len=in.read (buffer)) >0 indicates that in inside there is data                     while(len = in.read (buffer)) >0) {//Use the FileOutputStream output stream to write the buffer's data to the specified directory (savepath + "\ \"                        //+ filename)Out.write (Buffer,0, Len); }//Close input streamIn.close ();//Close output streamOut.close ();//Delete temporary files generated when processing file uploads                    //Item.delete ();Message ="File upload is successful!" "; }            }        }Catch(Fileuploadbase.filesizelimitexceededexception e)            {E.printstacktrace (); Request.setattribute ("Message","Single file exceeds maximum value!!!" "); Request.getrequestdispatcher ("/addproduct.jsp"). Forward (request, response);return; }Catch(Fileuploadbase.sizelimitexceededexception e)            {E.printstacktrace (); Request.setattribute ("Message","The total size of the uploaded file exceeds the maximum limit!!!" "); Request.getrequestdispatcher ("/addproduct.jsp"). Forward (request, response);return; }Catch(Exception e) {message ="File upload failed!" ";        E.printstacktrace (); } request.setattribute ("Message", message); Request.getrequestdispatcher ("/addproduct.jsp"). Forward (request, response); }/** * @Method: Makefilename * @Description: Generate the file name of the uploaded file, file name to: uuid+ "_" + the original name of the file * @Anth or: LMB * @param filename * The original name of the file * @return uuid+ "_" + the original name of the file */    PrivateStringMakefilename(String filename) {//2.jpg        //To prevent file coverage from happening, create a unique file name for the upload file        returnUuid.randomuuid (). toString () +"_"+ filename; }/** * To prevent too many files appearing under a directory, the hash algorithm is used to break the storage * * @Method: Makepath * @Description: *      @Anthor: LMB * * @param filename * file name, to generate the storage directory based on the file name * @param Savepath * File Storage path * @return New Storage directory */    PrivateStringMakepath(string filename, string savepath) {//Get the hashcode value of the filename, and get the address of this string object in memory        intHashcode = Filename.hashcode ();intDir1 = hashcode &0xf;//0--15        intDir2 = (Hashcode &0xf0) >>4;//0-15        //Construct a new save directoryString dir = Savepath +"\\"+ Dir1 +"\\"+ Dir2;//Upload\2\3                                                            //Upload\3\5        //file can represent both files and directoriesFile File =NewFile (dir);//If the directory does not exist        if(!file.exists ()) {//Create a directoryFile.mkdirs (); }returnDir } Public void DoPost(HttpServletRequest request, httpservletresponse response)throwsServletexception, IOException {doget (request, response); }}

upload.jsp (File upload on this page)

<%@ page language="java" import="java.util.*" pageencoding= "Utf-8"%><! DOCTYPE html><html>  <head>    <title>File Upload</title>  </head>  <body>    <form Action="upload.do" enctype="Multipart/form-data"  Method="POST">        <h2>Please select the image you want to upload:</H2>          <input type="file" name="File1"><br><br>          <input type="Submit" value="Submit">    </form>  </body></html>

Configuration in Web. xml:

<servlet> <description>this is  theDescription of myJava component</description> <display-name>this is  theDisplayname  of myJava component</display-name> <servlet-name>uploadservlet</servlet-name> <servlet-class>com.ymw.web.servlet.uploadservlet</servlet-class> </servlet><servlet-mapping> <servlet-name>uploadservlet</servlet-name> <url-pattern>/upload.do</url-pattern> </servlet-mapping>

Uploadresult.jsp (Show upload results on this page)

<%@ page language="java" import="java.util.*" pageencoding= "Utf-8"%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" ><html>  <head>    <title>Uploadresult page</title>  </head>  <body>${message}<br/><br/>File path:/images/${filename}</body></html>
Attention:

To get the filename and message in the foreground page, upload processing in the background must have

request.setAttribute("filename", filename);request.setAttribute("message", message);

======= Split line ===== above for file upload ===============

File download not finished ...

File upload download-servlet API implementation

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.