Home >Java >javaTutorial >Detailed tutorial on downloading java files (without parsing)

Detailed tutorial on downloading java files (without parsing)

php是最好的语言
php是最好的语言Original
2018-08-06 17:31:511806browse

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).

Detailed tutorial on downloading java files (without parsing)

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.

Detailed tutorial on downloading java files (without parsing)

That’s it.

This is equivalent to the resources in the server.

Detailed tutorial on downloading java files (without parsing)

Related recommendations:

java parsing XML files

java folder parsing

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn