Home > Java > javaTutorial > body text

How to download files from the web using Java?

WBOY
Release: 2023-04-24 20:31:06
forward
2043 people have browsed it

1. Download ideas

It is relatively simple to implement the file download function. You can directly use the Servlet class and input/output stream. To download a file, you not only need to specify the path of the file, but also set two response headers in the HTTP protocol:

//设定接受程序处理数据的方式
Content-Disposition:attachment; filename =
//设定试题内容的MIME类型
Content-Type:application/x-msdownload
Copy after login

Browsers generally directly process the entity content of the response. If you need to set these two response message header fields in the HTTP response message to specify the recipient to process the data content in a download mode, then when the Download hyperlink is clicked, the request will be submitted to the corresponding Servlet. In this Servlet, first obtain the address of the downloaded file, create a file byte input stream based on the address, then read the content of the downloaded file through the stream, and finally write the read content to the target file through the output stream.

2. Download example

File download download.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
 
<html>
 
<head>
 
    <title>Title</title>
 
</head>
 
<body>
 
   <img src="/file/ymkz.jpg" /><br>
 
   <a href="/DownloadServlet?filename=源码客栈.jpg">下载</a>
 
</body>
 
</html>
Copy after login

The above is the detailed content of How to download files from the web using Java?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!