首页 > 应用开发 > IT综合 > 通过OutputStream对文件又流的方式输出
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author:Lawmancs
* @version 1.0
*/
public class TestOutputStream extends HttpServlet {
/**
* Constructor of the object.
*/
public TestOutputStream () {
super();
}
/**
* Destruction of the servlet.
*/
public void destroy() {
super.destroy();
// Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet.
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String filename = request.getParameter("filename");
try {
String path = request.getRealPath("/") + "test.xls";
FileInputStream fileInput = new FileInputStream(path);
int i = fileInput.available();
byte[] content = new byte[i];
fileInput.read(content);
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename="
.concat(filename));
OutputStream output = response.getOutputStream();
output.write(content);
output.flush();
fileInput.close();
output.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* The doPost method of the servlet.
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/324336/viewspace-803191/ ,如需转载,请注明出处,否则将追究法律责任。