文件下载
来源:互联网 发布:上海网络推广公司 编辑:程序博客网 时间:2024/05/22 14:36
import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import javax.servlet.RequestDispatcher;import javax.servlet.ServletException;import javax.servlet.ServletOutputStream;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RestController@RequestMapping(value="/download")public class Download extends HttpServlet {@RequestMapping(value="download1")public void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {//获取文件下载路径String path = req.getServletContext().getRealPath("/").replace("\\", "/"); String filename = req.getParameter("filename");File file = new File(path +"images"+"\\"+ filename);if(file.exists()){//设置相应类型application/octet-streamresp.setContentType("application/x-msdownload");//设置头信息resp.setHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");InputStream inputStream = new FileInputStream(file);ServletOutputStream ouputStream = resp.getOutputStream();byte b[] = new byte[1024];int n ;while((n = inputStream.read(b)) != -1){ouputStream.write(b,0,n);}//关闭流、释放资源ouputStream.close();inputStream.close();}else{req.setAttribute("errorResult", "文件不存在下载失败!");RequestDispatcher dispatcher = req.getRequestDispatcher("jsp/a.jsp");dispatcher.forward(req, resp);}}public void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {doGet(req,resp);}}
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>Insert title here</title></head><body><a href="download/download1?filename=a.jpg">下载文件</a>${errorResult}</body></html>
阅读全文
0 0
- 下载图片,下载文件
- 文件下载
- 文件下载
- 文件下载
- 文件下载
- 文件下载
- 文件下载
- 下载文件
- 文件下载
- 下载文件
- 文件下载
- 文件下载
- 下载文件
- 文件下载
- 下载文件
- 下载文件
- 文件下载
- 下载文件
- Android 仿微博列表视频(一),静音播放
- c3p0数据库连接池+threadlocal线程池+DbUtils 进行数据库的操作
- 完美解决安卓RelativeLayout中android:layout_marginRight不生效
- java设计模式之单例模式
- CentOs 7 下安装Python3.5
- 文件下载
- LeetCode | 69. Sqrt(x)
- 欢迎使用CSDN-markdown编辑器
- POJ2785 -- 4 Values whose Sum is 0(折半枚举)
- MySQL NULL 值处理(转自https://www.w3cschool.cn/mysql/mysql-null.html)
- JAVA实现线程同步
- PrintWriter和BufferedWriter的使用区别
- Java生成验证码
- [Project] Online Notes App