`

servle+jspt文件下载

 
阅读更多
jsp code
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
<form action="<c:url value='/CosServlet'/>" method="post"
enctype="multipart/form-data">
File1:<input type="file" name="img1"><br /> 说明1:<input
type="text" name="desc1"><br />
<%--
    File2:<input type="file" name="img2"><br/>
    说明2:<input type="text" name="desc2"><br/>
    File3:<input type="file" name="img3"><br/>
    说明3:<input type="text" name="desc3"><br/>
    --%>
<input type="submit" />
</form>
<hr />
<a href="<c:url value='/up/a.jpg'/>">下载jpg</a>
<br />
<a href="<c:url value='/up/cos.jar'/>">下载jar</a>
<br />
<br />
<a href="<c:url value='/DownServlet'/>">下载/Servlet</a>
<br />
<hr />
<form action="<c:url value='/DownServlet'/>" method="post">
请输入 <input type="text" id="fileName" name="name"><br /> <input
type="submit" value="下载" />
</form>
</body>
</html>







java code
package cn.itcast;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DownServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}

public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
String name = req.getParameter("name");
//第一步:设置响应的类型
resp.setContentType("application/force-download");
//第二读取文件
String path = getServletContext().getRealPath("/up/"+name);
InputStream in = new FileInputStream(path);
//设置响应头
//对文件名进行url编码
name = URLEncoder.encode(name, "UTF-8");
resp.setHeader("Content-Disposition","attachment;filename="+name);
resp.setContentLength(in.available());

//第三步:开始文件copy
OutputStream out = resp.getOutputStream();
byte[] b = new byte[1024];
int len = 0;
while((len=in.read(b))!=-1){
out.write(b,0,len);
}
out.close();
in.close();
}

}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics