Este artigo compartilha o código específico para download do arquivo servlet para sua referência. O conteúdo específico é o seguinte
Não é seguro expor o diretório de arquivos diretamente ao usuário. Portanto, você precisa usar servlets e, dessa maneira, os arquivos serão armazenados de maneira mais abundante. Eles podem ser recuperados do sistema de arquivos, gerados por cálculos no banco de dados ou recuperados de outros lugares estranhos.
classe pública DownloadServlet estende httpServlet {private string contentType = "Application/x-msDownload"; String privada ENC = "UTF-8"; private string fileroot = ""; / ** * Initialize contentType, ENC, FileRoot */ public void init (servletConfig config) lança servletexception {string tempstr = config.getInitParameter ("contentType"); if (tempstr! = null &&! tempstr.equals ("" ")) {contentType = tempstr; } tempstr = config.getInitParameter ("ENC"); if (tempstr! = null &&! tempstr.equals ("")) {Enc = tempstr; } tempstr = config.getInitParameter ("FILEROOT"); if (tempstr! = null &&! tempstr.equals ("")) {fileroot = tempstr; }} Void protegido Doget (solicitação httpServletRequest, resposta httpServletResponse) lança servletexception, ioexception {string filepath = request.getParameter ("filepath"); String fullFilePath = filroot + filepath; /*Leia o arquivo*/ arquivo de arquivo = novo arquivo (FullFilePath); /*Se o arquivo existir*/ if (file.exists ()) {string filename = urlencoder.encode (file.getName (), ENC); Response.Reset (); Response.setContentType (contentType); Response.addHeader ("Content-Disposition", "Anexamento; nome do arquivo =/" " + nome do arquivo +"/""); int fileLength = (int) file.length (); Response.setContentLength (comprimento do arquivo); /*Se o comprimento do arquivo for maior que 0*/ if (fileLength! = 0) {/*Crie fluxo de entrada*/ inputStream Instruam = new FileInputStream (arquivo); byte [] buf = novo byte [4096]; /*Crie fluxo de saída*/ servletOutputStream servletos = Response.getOutputStream (); Int ReadLength; while (((readLength = Instream.read (BUF))! = -1)) {servletos.write (buf, 0, comprimento de leitura); } unstruam.close (); servletos.flush (); servletos.close (); }}} web.xml
<Verlet> <Verlet-name> DownloadServlet-NAME> <Verlet-class-class> org.mstar.servlet.downloadservletletServlet-class> <iit-param> <amam-name> filerootparam-name> <amam-value> d:/tempparam-value> init-paparm> <inter-param> renty> <Maver-Value> Application/X-MsDownloadParam-Value> init-param> <iit-param> <amam-name> Encparam-name> <amam-value> utf-8param-value >>> init-param> servlet> <arerlet-mapping> <verlet-name> downloadname> <rever-Pattern>/-Pattern>/-Pattern>/-Pattern>/-PLAPTN>/-PLAPTN>/-MAPTERN>/Pattern>/Pattern>/Mertletname>/url-maternames>
O exposto acima é todo o conteúdo deste artigo. Espero que seja útil para o aprendizado de todos e espero que todos apoiem mais o wulin.com.