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