Java 从服务器下载文件到本地(页面、后台、配置都有)
先来看实现效果:
有一个链接如下:

点击链接下载文件:

第一种方法:Servlet实现
一、HTML页面部分:
1、HTML页面中的一个链接
<a id="downloadTemplate" style="color:blue" onclick="download();">下载导入模板</a>
2、引入JS
function download(){
downloadTemplate('downloadExel.downloadexcel', 'filename', 'project');
}
/**
* 用于下载导入模板时的影藏form表单的提交,采用post方式提交
* @param action action映射地址
* @param type parameter的名称
* @param value parameter的值,这里为file的filename
*/
function downloadTemplate(action, type, value){
var form = document.createElement('form');
document.body.appendChild(form);
form.style.display = "none";
form.action = action;
form.id = 'excel';
form.method = 'post';
var newElement = document.createElement("input");
newElement.setAttribute("type","hidden");
newElement.name = type;
newElement.value = value;
form.appendChild(newElement);
form.submit();
}
3、解释上面JS(不是正是代码)
相当于提交一个form,里面如下:
<input type=hidden name="filename" value = "project">
后台可以通过下面代码获得文件名:project
String filename = request.getParameter("filename");
(这段是上面js的翻译,不是正式的哦)
二、配置部分
配置前台页面和后台交互
1、web.xml配置
<?xml version="1.0" encoding="UTF-8"?> <web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <servlet>
<servlet-name>downloadServlet</servlet-name>
<servlet-class>
com.zit.rfid.app.prms.business.service.servlet.DownloadTemplateServlet
</servlet-class>
<load-on-startup></load-on-startup>
</servlet> <servlet-mapping>
<servlet-name>downloadServlet</servlet-name>
<url-pattern>*.downloadexcel</url-pattern>
</servlet-mapping>
</web-app>
我这个web.xml不是整个工程的web.xml,只是一个模块的,在你的web.xml加入上面servlet和servlet-mapping里的内容即可
如上:
(1)接受 *.downloadexcel 的Action
(2)HTML的JS里的Action,交给com.test.DownloadTemplateServlet这个类去处理
2、WebContent目录下新建file文件夹,存放project.xls文件 (Eclipse的Web工程有WebContent,MyEclipse好像是WebRoot)

三、后台部分
1、新建一个servlet:
DownloadTemplateServlet.java
package com.test; import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URLEncoder; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* @author 0223000218
* 主要用于下载导入模板,页面上传入的request中parameter中,filename代表了要下载的模板的名称
*/
public class DownloadTemplateServlet extends HttpServlet { /**
* serialVersionUID
*/
private static final long serialVersionUID = -4541729035831587727L; private final static String HOME_PATH = DownloadTemplateServlet.class.getResource("/").getPath();
private final static String DOWNLOAD_TEMP_FILE = HOME_PATH.subSequence(, HOME_PATH.indexOf("WEB-INF")) + "file/"; @Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
} @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String filename = req.getParameter("filename");
try{
resp.reset();// 清空输出流 String resultFileName = filename + System.currentTimeMillis() + ".xls";
resultFileName = URLEncoder.encode(resultFileName,"UTF-8");
resp.setCharacterEncoding("UTF-8");
resp.setHeader("Content-disposition", "attachment; filename=" + resultFileName);// 设定输出文件头
resp.setContentType("application/msexcel");// 定义输出类型
//输入流:本地文件路径
DataInputStream in = new DataInputStream(
new FileInputStream(new File(DOWNLOAD_TEMP_FILE + filename + ".xls")));
//输出流
OutputStream out = resp.getOutputStream();
//输出文件
int bytes = ;
byte[] bufferOut = new byte[];
while ((bytes = in.read(bufferOut)) != -) {
out.write(bufferOut, , bytes);
}
out.close();
in.close();
} catch(Exception e){
e.printStackTrace();
resp.reset();
try {
OutputStreamWriter writer = new OutputStreamWriter(resp.getOutputStream(), "UTF-8");
String data = "<script language='javascript'>alert(\"\\u64cd\\u4f5c\\u5f02\\u5e38\\uff01\");</script>";
writer.write(data);
writer.close();
} catch (IOException e1) {
e1.printStackTrace();
}
} } }
大致步骤:
1. 获取服务器文件所在路径
2. 输入服务器文件
3. 输出文件到本地
第二种方法:SpringMVC实现
这种方法比较简单
一、JSP页面部分
和上面一样
<a id="downloadTemplate" style="color:blue" onclick="download();">下载导入模板</a>
//导出模板下载
function download(){
//后台方法、文件类型、文件名
downloadTemplate('${pageContext.request.contextPath}/cardIssueVehicleInfo/exportVehicleInfo', 'filename', 'test');
} /**
* 用于下载导入模板时的影藏form表单的提交,采用post方式提交
* @param action 请求后台方法
* @param type 文件类型
* @param value 文件名
*/
function downloadTemplate(action, type, value){
var form = document.createElement('form');
document.body.appendChild(form);
form.style.display = "none";
form.action = action;
form.id = 'excel';
form.method = 'post'; var newElement = document.createElement("input");
newElement.setAttribute("type","hidden");
newElement.name = type;
newElement.value = value;
form.appendChild(newElement); form.submit();
}
二、后台部分
@RequestMapping("exportVehicleInfo")
public void exportVehicleInfo(HttpServletRequest req, HttpServletResponse resp) {
String filename = req.getParameter("filename");
DataInputStream in = null;
OutputStream out = null;
try{
resp.reset();// 清空输出流
String resultFileName = filename + System.currentTimeMillis() + ".xls";
resultFileName = URLEncoder.encode(resultFileName,"UTF-8");
resp.setCharacterEncoding("UTF-8");
resp.setHeader("Content-disposition", "attachment; filename=" + resultFileName);// 设定输出文件头
resp.setContentType("application/msexcel");// 定义输出类型
//输入流:本地文件路径
in = new DataInputStream(
new FileInputStream(new File(downloadPath + "test.xls")));
//输出流
out = resp.getOutputStream();
//输出文件
int bytes = ;
byte[] bufferOut = new byte[];
while ((bytes = in.read(bufferOut)) != -) {
out.write(bufferOut, , bytes);
}
} catch(Exception e){
e.printStackTrace();
resp.reset();
try {
OutputStreamWriter writer = new OutputStreamWriter(resp.getOutputStream(), "UTF-8");
String data = "<script language='javascript'>alert(\"\\u64cd\\u4f5c\\u5f02\\u5e38\\uff01\");</script>";
writer.write(data);
writer.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}finally {
if(null != in) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(null != out) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Java 从服务器下载文件到本地(页面、后台、配置都有)的更多相关文章
- 使用xshell从远程服务器下载文件到本地
XSHELL工具上传文件到Linux以及下载文件到本地(Windows) Xshell很好用,然后有时候想在windows和linux上传或下载某个文件,其实有个很简单的方法就是rz,sz.首先你的L ...
- 从Linux服务器下载文件到本地命令
从Linux服务器下载文件夹到本地1.使用scp命令 scp /home/work/source.txt work@192.168.0.10:/home/work/ #把本地的source.txt文件 ...
- java 从服务器下载文件并保存到本地
昨天在做一个项目时,用到了从服务器上下载文件并保存到本地的知识,以前也没有接触过,昨天搞了一天,这个小功能实现了,下面就简单的说一下实现过程: 1.基础知识 当我们想要下载网站上的某 ...
- Java实现从服务器下载文件到本地的工具类
话不多说,直接上代码...... import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServlet ...
- 从Linux服务器下载文件到本地
通过安装xshell,连接服务器,通过以下命令可以方便的将服务器的文件下载到本地 #下载一个文件 sz filename #下载多个文件 sz filename1 filename2 #下载dir目录 ...
- 使用scp从远程服务器下载文件到本地
[下载远程文件到本地] scp -P 6008 root@192.168.1.123:/usr/data/1.zip /Users/abc/www [上传本地文件到远程] scp -P 6008 ...
- 使用“rz -be”命令上传文件至服务器;使用“sz 文件名”从服务器下载文件到本地
注意:需要事先安装lrzsz服务 yum install -y lrzsz 因为服务器没有安装sftp服务,无法使用FileZilla.Xftp等连接服务器上传文件,这种情况可以利用rz命令上传文件. ...
- JAVA从服务器下载文件根据Url把多文件打包成ZIP下载
注意: 1. String filename = new String(“xx.zip”.getBytes(“UTF-8”), “ISO8859-1”);包装zip文件名不发生乱码. 2.一定要注意 ...
- python urllib从远程服务器下载文件到本地
#!/usr/bin/env python #-*-coding:utf--*-' #Filename:download_file.py import sys,os import urllib def ...
随机推荐
- 2018 AICCSA Programming Contest
2018 AICCSA Programming Contest A Tree Game B Rectangles 思路:如果存在大于0的交面积的话, 那么肯定能找到一条水平的直线 和 一条垂直的直线, ...
- 常用的 git 命令
更新 : 2019-03-02 写一个常用流程比较清楚 : 项目开始 : git clone ... git add file git commit -m "whatever" g ...
- 安卓中使用HttpURLConnection连接网络简单示例 --Android网络编程
MainActivity.java: package thonlon.example.cn.httpurlconnectionpro; import android.os.Bundle;import ...
- OSPF - 1,基础
1,OSPF知识点a)在OSPF中,如果是环回口宣告进OSPF,不管宣告时配置的是多少位掩码,路由器收到的都是32位.(EIGRP配了多少位就收到多少位).好处:EIGRP中,在PING包发起时如果在 ...
- You Don't Know JS: Async & Performance(第3章, Promises)(未看)
Chapter 3: Promises But what if we could uninvert that inversion of control? What if instead of hand ...
- sgu 169 Numbers
题意:n和n+1同时被数位乘积整除的k位数个数. 假如a是237,b是238.由于个位以前的数一样.那么对于2,如果a%2==0,b%2就!=0,如果a%3==0,b%3就!=0.因此个位以前的数只能 ...
- 基于散列的集合 HashSet\HashMap\HashTable
HashSet\HashMap\HashTable 1 基于散列的集合 2 元素会根据hashcode散列,因此,集合中元素的顺序不一定与插入的顺序一致. 3 根据equals方法与hashCode方 ...
- python记录_day27 tcp/ip五层模型
## 网络协议按照不同的功能分为多层,目前存在的模型有osi七层模型.tcp/ip五层和tcp/ip四层模型 我们主要用的是tcp/ip五层模型 那么每层的作用是什么呢,现在就从设计者的角度自下到上逐 ...
- CentOS7 搭建LVS+keepalived负载均衡
1.实验环境 4台节点 Keepalived1 + lvs1(Director1):192.168.31.4 Keepalived2 + lvs2(Director2):192.168.31.3 Re ...
- python-django中间件session源码
settings.py MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', ] 1. 看看SessionMid ...