文件下载

来源:互联网 发布:上海网络推广公司 编辑:程序博客网 时间: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>


原创粉丝点击