您的位置:首页 > 编程语言 > Java开发

java从服务器下载xls文件到客户端

2010-07-28 16:27 417 查看
查考网上的代码写了一个下载xls文件到客户端的jsp页面,只要将服务器的文件地址传给这个jsp页面就可以实现下载文件到客户端了。

Code:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%@ page import="java.io.*" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<link href="styles/basic.css" rel="stylesheet" type="text/css" />

<title>download</title>

</head>

<%

response.setCharacterEncoding("gb2312");

request.setCharacterEncoding("gb2312");



if (request.getParameter("file") != null) {

OutputStream os = null;

FileInputStream fis = null;

try {

String file = request.getParameter("file");

if (!(new File(file)).exists()) {

System.out.println("没有文件");

return;

}

System.out.println("文件名为:"+file);

os = response.getOutputStream();

response.setHeader("content-disposition", "attachment;filename=" + file);

response.setContentType("application/vnd.ms-excel");//此项内容随文件类型而异

byte temp[] = new byte[1000];

fis = new FileInputStream(file);

int n = 0;

while ((n = fis.read(temp)) != -1) {

os.write(temp, 0, n);

}

} catch (Exception e) {

out.print("出错");

} finally {

if (os != null)

os.close();

if (fis != null)

fis.close();

}

out.clear();

out = pageContext.pushBody();



}

%>



<form action="" method="post">

<select name="file">

<option value="D://test//test.xls">

冷山sky_snow

</option>

</select>

<input type="submit"/>

</form>

</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: