servlet download File

Source: Internet
Author: User

1. Get the project root directory:

@Override      Public void throws servletexception {        //  Gets the project's root directory in the file system        string = getservletcontext (). Getrealpath (File.separator);    }

The init () method is only loaded once throughout the servlet life cycle for initialization of data.

2. Download the file code:

@Overrideprotected voiddoget (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {//configuration file pathString FilePath = string + "Download" + file.separator + "18612.jpg"; //get the universe's unique file name through the UUID and remove the '-' connectorString Filename=uuid.randomuuid (). toString (). Replace ("-", "" "); //set Download file nameResponse.setheader ("Content-disposition",                "Attachment;filename=" +filename+ ". jpg"); //Get output streamServletoutputstream OutputStream =Response.getoutputstream (); //write files to TomcatInputStream InputStream =NewFileInputStream (NewFile (FilePath)); byte[] B =New byte[1024]; intLen = 0;  while(len = Inputstream.read (b))! =-1) {            //Output to BrowserOutputstream.write (b, 0, Len); }        if(inputstream!=NULL) {inputstream.close (); }        if(outputstream!=NULL) {outputstream.close (); }    }

servlet download File

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.