下载文件
package com.xxx.servlet;
import jdk.internal.util.xml.impl.Input;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
@WebServlet("/downFile")
public class downFile extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
String fileName=req.getParameter("fileName");
System.out.println("Name "+fileName);
if(fileName==null||"".equals(fileName.trim())) {
System.out.println("null");
return;
}
String path=req.getServletContext().getRealPath("/download/");
//文件下载
File file=new File(path+fileName);
if(file.exists()&&file.isFile()){
//设置响应类型
resp.setContentType("application/x-msdownload");
//设置响应头
resp.setHeader("Content-Disposition","attchment;filename="+fileName);
//输入流
InputStream in=new FileInputStream(file);
//输出流
ServletOutputStream out=resp.getOutputStream();
byte[] data=new byte[1024];
int len=0;
while((len=in.read(data))!=-1){
out.write(data,0,len);
}
}
}
}
文件存放
1.放入download文件夹内
2.设置edit config
3.访问html路径
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!-- 浏览器可识别 会显示内容-->
<a href="download/test.txt">click</a><br>
<!-- 浏览器不可识别 会提示下载-->
<a href="download/test.zip">click</a><br>
<!-- 使用download属性-->
<a href="download/test.txt" download="test.txt">click</a><br>
<form action="downFile" method="post">
FileName: <input type="text" name="fileName" placeholder="FileName">
<button type="submit">submit</button>
</form>
</body>
</html>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律