以Java web的方式下载服务器文件到浏览器
请求例子:localhost:8080/downExcel?excel=文件名.xls
示例代码:
一:允许Spring Boot使用Java web
在spring boot启动器中添加@ServletComponentScan注解
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
@SpringBootApplication
@ServletComponentScan //这里
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
二:文件下载
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/downExcel")
public class DownExcel extends HttpServlet {
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
//获取前端传递参数
String excel=request.getParameter("excel");
File file = null;
try {
//通过相对路径查找文件
file = new File("excel/" + excel);
} catch (Exception e) {
}
response.setContentType("application/x-xls");
// 判断文件是否存在,存在才下载
if (file.exists()) {
OutputStream out = null;
FileInputStream in = null;
try {
// 读取要下载的内容
in = new FileInputStream(file);
//设置请求头
String agent = request.getHeader("user-agent");
//设置导出文件的名字
String filename = "文件导出.xls";
// 解决文件名乱码问题,
// IE要求文件名必须是utf-8,
// firefo要求是iso-8859-1编码
if (agent.contains("FireFox")) {
filename = new String(filename.getBytes("UTF-8"), "iso-8859-1");
} else {
filename = URLEncoder.encode(filename, "UTF-8");
}
// 设置下载文件的mineType,告诉浏览器下载文件类型
String mineType = request.getServletContext().getMimeType(filename);
response.setContentType(mineType);
// 设置一个响应头,无论是否被浏览器解析,都下载
response.setHeader("Content-disposition", "attachment; filename=" + filename);
// 将要下载的文件内容通过输出流写到浏览器
out = response.getOutputStream();
int len = 0;
byte[] buffer = new byte[1024];
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
}
}
} catch (Exception e) {
}
}
}