JAVA上传与下载
java下载指定地址的文件
package com.test;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TestFile {
public static void main(String[] args) {
try {
int byteSum = 0;//已下载字节数
int byteRead = 0;//读取字节数
int byteCount = 0;//总字节数
String filePath = "http://123.157.149.169/down/37f3e48bf5a412ea27f01be2b5e00a4c-18173940/%5BROSI%5D2013.09.22%20NO.659%5B25%2B1P%5D.rar?cts=223A167A86A3&ctp=223A167A86A3&ctt=1379946470&limit=3&spd=0&ctk=0d4b4e4b39e9b9a1c8d4104e07a79c90&chk=37f3e48bf5a412ea27f01be2b5e00a4c-18173940&mtd=1";
URL url = new URL(filePath);
URLConnection conn = url.openConnection();
//获取文件名
String path = url.getPath();
Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssms");
String fileName = sdf.format(d) + path.substring(path.lastIndexOf("."));
System.out.println("文件名称:"+ fileName );
//获取总字节数
byteCount = conn.getContentLength();
double len = Double.parseDouble(byteCount+"")/(1024*1024);
DecimalFormat df = new DecimalFormat("0.##");
System.out.println("文件大小:" + df.format(len) + "MB");
InputStream inStream = conn.getInputStream();
FileOutputStream fs = new FileOutputStream("E:/"+fileName);
byte[] buffer = new byte[1204];
System.out.println("文件开始下载....");
while (( byteRead = inStream.read(buffer)) != -1) {
byteSum += byteRead;
int num = byteSum*100/Integer.parseInt(byteCount+"");
System.out.println("已下载"+ num +"%....");
fs.write(buffer, 0, byteRead);
}
System.out.println("文件下载完成!");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
java如何将导出的excel下载到客户端
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 利用Servlet导出Excel
* @author CHUNBIN
*
*/
public class ExportExcelServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");//设置request的编码方式,防止中文乱码
String fileName ="导出数据";//设置导出的文件名称
StringBuffer sb = new StringBuffer(request.getParameter("tableInfo"));//将表格信息放入内存
String contentType = "application/vnd.ms-excel";//定义导出文件的格式的字符串
String recommendedName = new String(fileName.getBytes(),"iso_8859_1");//设置文件名称的编码格式
response.setContentType(contentType);//设置导出文件格式
response.setHeader("Content-Disposition", "attachment; filename=" + recommendedName + "\"");//
response.resetBuffer();
//利用输出输入流导出文件
ServletOutputStream sos = response.getOutputStream();
sos.write(sb.toString().getBytes());
sos.flush();
sos.close();
}
}
<%@ 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>导出Excel</title>
<script type="text/javascript">
function test(){
document.getElementById("tableInfo").value=document.getElementById("table").innerHTML;
}
</script>
<style>
body{font-family:宋体;font-size:11pt}
</style>
</head>
<body>
<form action="<%=request.getContextPath()%>/servlet/ExportExcelServlet" method="post">
<span id="table">
<table bgcolor="#EEECF2" bordercolor="#A3B2CC" border="1" cellspacing="0">
<tr><th>学号</th><th>姓名</th><th>科目</th><th>分数</th></tr>
<tr><td>10001</td><td>赵二</td><td>高数</td><td>82</td></tr>
<tr><td>10002</td><td>张三</td><td>高数</td><td>94</td></tr>
<tr><td>10001</td><td>赵二</td><td>线数</td><td>77</td></tr>
<tr><td>10002</td><td>张三</td><td>线数</td><td>61</td></tr>
</table>
</span>
<input type="submit" name="Excel" value="导出表格" onclick="test()"/>
<input type="hidden" id="tableInfo" name="tableInfo" value=""/>
</form>
</body>
</html>
upload_json.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.util.*,java.io.*"%>
<%@ page import="java.text.SimpleDateFormat"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page import="org.apache.commons.fileupload.disk.*"%>
<%@ page import="org.apache.commons.fileupload.servlet.*"%>
<%@ page import="com.opensymphony.xwork2.ActionContext"%>
<%@ page
import="org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper"%>
<%@ page import="org.json.simple.*"%>
<%
//文件保存目录路径
String savePath = pageContext.getServletContext().getRealPath("/")
+ "kindeditor/attached/";
//文件保存目录URL
String saveUrl = request.getContextPath() + "/kindeditor/attached/";
//定义允许上传的文件扩展名
HashMap<String, String> extMap = new HashMap<String, String>();
extMap.put("image", "gif,jpg,jpeg,png,bmp");
extMap.put("flash", "swf,flv");
extMap.put("media",
"swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
extMap.put("file",
"doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");
//最大文件大小
long maxSize = 1000000;
response.setContentType("text/html; charset=UTF-8");
if (!ServletFileUpload.isMultipartContent(request)) {
out.println(getError("请选择文件。"));
return;
}
//检查目录
File uploadDir = new File(savePath);
if (!uploadDir.isDirectory()) {
out.println(getError("上传目录不存在。"));
return;
}
//检查目录写权限
if (!uploadDir.canWrite()) {
out.println(getError("上传目录没有写权限。"));
return;
}
String dirName = request.getParameter("dir");
if (dirName == null) {
dirName = "image";
}
if (!extMap.containsKey(dirName)) {
out.println(getError("目录名不正确。"));
return;
}
//创建文件夹
savePath += dirName + "/";
saveUrl += dirName + "/";
File saveDirFile = new File(savePath);
if (!saveDirFile.exists()) {
saveDirFile.mkdirs();
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String ymd = sdf.format(new Date());
savePath += ymd + "/";
saveUrl += ymd + "/";
File dirFile = new File(savePath);
if (!dirFile.exists()) {
dirFile.mkdirs();
}
MultiPartRequestWrapper wrapper = (MultiPartRequestWrapper) request;
//获得上传的文件名
String fileName = wrapper.getFileNames("imgFile")[0];//imgFile,imgFile,imgFile
//获得文件过滤器
File file = wrapper.getFiles("imgFile")[0];
//检查扩展名
String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1)
.toLowerCase();
if (!Arrays.<String> asList(extMap.get(dirName).split(","))
.contains(fileExt)) {
out.println(getError("上传文件扩展名是不允许的扩展名。\n只允许"
+ extMap.get(dirName) + "格式。"));
return;
}
//检查文件大小
if (file.length() > maxSize) {
out.println(getError("上传文件大小超过限制。"));
return;
}
//重构上传图片的名称
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String newImgName = df.format(new Date()) + "_"
+ new Random().nextInt(1000) + "." + fileExt;
byte[] buffer = new byte[1024];
//获取文件输出流
FileOutputStream fos = new FileOutputStream(savePath + "/"
+ newImgName);
//System.out.println("########" + saveUrl + "@@"+ newImgName);
//获取内存中当前文件输入流
InputStream in = new FileInputStream(file);
try {
int num = 0;
while ((num = in.read(buffer)) > 0) {
fos.write(buffer, 0, num);
}
} catch (Exception e) {
e.printStackTrace(System.err);
} finally {
in.close();
fos.close();
}
JSONObject obj = new JSONObject();
obj.put("error", 0);
obj.put("url", saveUrl + newImgName);
out.println(obj.toJSONString());
%>
<%!private String getError(String message) {
JSONObject obj = new JSONObject();
obj.put("error", 1);
obj.put("message", message);
return obj.toJSONString();
}%>
struts下载文件配置
public String download() throws Exception {
uploadFileName="中文.jpg";
downStream = ServletActionContext.getServletContext()
.getResourceAsStream(inputPath);
return SUCCESS;
}
<action name="download" class="upload.DownloadAction" method="download">
<!-- 指定被下载资源的位置 -->
<param name="inputPath">\download\中文.jpg</param>
<!-- 配置结果类型为stream的结果 -->
<result name="success" type="stream">
<!-- 指定返回下载文件的InputStream -->
<param name="inputName">downStream</param>
<!-- 指定下载文件的文件类型 -->
<param name="contentType">image/jpg</param>
<param name="contentDisposition">attachment;filename=${uploadFileName}</param>
<!-- 指定下载文件的缓冲大小 -->
<param name="bufferSize">4096</param>
</result>
<result name="input">/upload.jsp
</result>
</action>
页面
<a href="download.action">下载包含中文文件名的文件</a>
/这一段代码我也是不知道是哪里的 先放上去 以后再看吧
public String executeCommandUDownload(ActionContext context)throws Exception{
HttpServletResponse response = context.getResponse();
response.setCharacterEncoding("UTF-8");
boolean isOnLine = false;
String fileName = context.getRequest().getParameter("fileName");
Connection con = null;
HttpServletRequest request = context.getRequest();
String filePath = null;
BufferedInputStream buffer=null;
OutputStream out=null;
try
{
con = this.getConnection(context);
if("".equals(fileName) || fileName == null){
FileInfoBean bean = new FileInfoBean();
fileName = bean.findName(con, id);
}
File f = new File(filePath);
//检查该文件是否存在
if(!f.exists()){
response.sendError(404,"File not found!");
return "File not found!";
}
buffer = new BufferedInputStream(new FileInputStream(f));
byte[] buf = new byte[1024];
int len = 0;
response.reset(); //非常重要
if(isOnLine){ //在线打开方式
URL u = new URL("file:///"+filePath);
response.setContentType(u.openConnection().getContentType());
response.setHeader("Content-Disposition", "inline; filename="+(f.getName()).getBytes("gbk"));
//文件名应该编码成UTF-8
}
else{ //纯下载方式
response.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(f.getName(),"UTF-8"));
}
out = response.getOutputStream();
while((len = buffer.read(buf)) >0)
out.write(buf,0,len);
}catch(Throwable e)
{
e.printStackTrace();
}finally
{
try
{
buffer.close();
out.close();
}catch(Throwable e)
{
e.printStackTrace();
}
}
return "";
}
JAVA上传与下载的更多相关文章
- java上传、下载、删除ftp文件
一共三个类,一个工具类Ftputil.,一个实体类Kmconfig.一个测试类Test 下载地址:http://download.csdn.net/detail/myfmyfmyfmyf/669710 ...
- java上传并下载以及解压zip文件有时会报文件被损坏错误分析以及解决
情景描述: 1.将本地数据备份成zip文件: 2.将备份的zip文件通过sftp上传到文件服务器: 3.将文件服务器上的zip文件下载到运行服务器: 4.将下载的zip文件解压到本地(文件大小超过50 ...
- Java上传和下载
1.文件的上传 [1] 简介 > 将一个客户端的本地的文件发送到服务器中保存. > 上传文件是通过流的形式将文件发送给服务器. [2] 表单的设置 > 向服务器上传一个文件时,表单要 ...
- Java web实时进度条整个系统共用(如java上传、下载进度条、导入、导出excel进度条等)
先上图: 文件上传的: 2017-05-04再次改进.在上传过程中用户可以按 Esc 来取消上传(取消当前上传,或者是全部上传)... 2019-03-26更新进度条显示体验 从服务器上压缩下载: 从 ...
- Java实现FTP文件与文件夹的上传和下载
Java实现FTP文件与文件夹的上传和下载 FTP 是File Transfer Protocol(文件传输协议)的英文简称,而中文简称为"文传协议".用于Internet上的控制 ...
- java web学习总结(二十四) -------------------Servlet文件上传和下载的实现
在Web应用系统开发中,文件上传和下载功能是非常常用的功能,今天来讲一下JavaWeb中的文件上传和下载功能的实现. 对于文件上传,浏览器在上传的过程中是将文件以流的形式提交到服务器端的,如果直接使用 ...
- java实现ftp文件的上传与下载
最近在做ftp文件的上传与下载,基于此,整理了一下资料.本来想采用java自带的方法,可是看了一下jdk1.6与1.7的实现方法有点区别,于是采用了Apache下的框架实现的... 1.首先引用3个包 ...
- java文件上传和下载
简介 文件上传和下载是java web中常见的操作,文件上传主要是将文件通过IO流传放到服务器的某一个特定的文件夹下,而文件下载则是与文件上传相反,将文件从服务器的特定的文件夹下的文件通过IO流下载到 ...
- Java实现FTP文件上传与下载
实现FTP文件上传与下载可以通过以下两种种方式实现(不知道还有没有其他方式),分别为:1.通过JDK自带的API实现:2.通过Apache提供的API是实现. 第一种方式 package com.cl ...
随机推荐
- 荣获MVP感想
感言 最近特别忙,除了工作之外最开心的算是收到了MVP的奖杯,从到申请到审批通过也不过一个礼拜的时间,从去年就开始想着是否应该一试,通过和张善友大哥的沟通抱着试一试的忐忑结果意外惊喜通过了,由于每月申 ...
- ECMAScript迭代语句
迭代语句又叫循环语句,声明一组要反复执行的命令,直到满足某些条件为止. 循环通常用于迭代数组的值(因此而得名),或者执行重复的算术任务. do-while, while, for, for-in -- ...
- hdu3555 Bomb 数位DP入门
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3555 简单的数位DP入门题目 思路和hdu2089基本一样 直接贴代码了,代码里有详细的注释 代码: ...
- 学习笔记:javascript 窗口对象(window)
1.窗口对象属性 属性 描述 closed 返回窗口是否已被关闭. defaultStatus 设置或返回窗口状态栏中的默认文本. document 对 Document 对象的只读引用.请参阅 Do ...
- UML学习笔记之类之间的关系
1. 导航关系(Directed Association) A类有一个成员变量保存B的引用. 2.包含关系(Aggregation.Composition) (1)弱包含 含义:每个部门包含多个 ...
- wamp的搭建-个人笔记
#wamp的配置 ##选项 1. 用apache 就下ts的 2. 是nginx或者iis 就用nts的 3. php win下面的 选择zip 或者msi的 ##apache的配置 1.配置apac ...
- 连续分段累计器FPGA实现的探讨
- javascript基础-闭包
原理 函数里包含函数,即闭包. 包含函数的结果是,子函数会挟持父函数的活动对象.子函数在访问一个变量时,先读自身的活动对象,是否包含此变量,没有从父函数里找,还没有,去祖函数,层层回溯,直到windo ...
- 入职这一段时间的总结,Don't Repeat Yourself.
1.第一次接触到大型软件系统的开发,现在我们使用的是 python + flask +vue.js ,数据库:postgresql 2. 不要在自己不懂的情况下复制代码,每次分析一段代码的时候,就跟以 ...
- [HDU1004] Let the balloon rise - 让气球升起来
Problem Description Contest time again! How excited it is to see balloons floating around. But to te ...