Home >Java >javaTutorial >Detailed tutorial on downloading java files (without parsing)
First, let’s talk about the servlets that have been studied recently. A servlet is a piece of code that is executed on the server.
servlet has three standard servlet technologies, listener technology - listener, and filer technology - filter. The last two will be introduced in future blogs. Let’s talk about what a ServletContext object is. The ServletContext object represents a web application environment (context), and there is only one ServletContext object for a web application.
ServletContext is a domain object - what is stored in the data area is the domain object, and its scope is all web resources.
Let’s talk about how to download the file. If you put the file on the server (the computer of the published website).
This is fine, but you will encounter this situation. I want to download the jpg format, but the browser opens directly and does not download, but the zip format can be downloaded. This needs to be set through code to prevent the browser from parsing it. This is ready for download.
Create a new Servlet file and write it in the get code.
//解决获得中文参数的乱码 filename=new String(filename.getBytes("ISO8859-1"),"UTF-8"); //要下载的文件的类型--客户端通过文件的MIME类型去区分类型 response.setContentType(this.getServletContext().getMimeType(filename)); //告诉客户端该文件不是直接解析而是以附件的形式打开(下载) response.setHeader("Content-Disposition", "attachment;filename="+filename); //收获文件的绝对路径 String path = this.getServletContext().getRealPath("download/"+filename); //获得文件的输入流 FileInputStream in = new FileInputStream(path); //获得输出流--通过response获得输出流用于向客户端写内容 ServletOutputStream out = response.getOutputStream(); //文件拷贝的模板代码 int len=0; byte[] buffer=new byte[1024]; while((len=in.read(buffer))>0){ out.write(buffer, 0, len); } in.close(); out.close();
This out can be closed or not, but in needs to be closed because it is new in the program. out will automatically close after running the program.
That’s it.
This is equivalent to the resources in the server.
Related recommendations:
The above is the detailed content of Detailed tutorial on downloading java files (without parsing). For more information, please follow other related articles on the PHP Chinese website!