您的位置:首页

文件下载

2016-03-28 18:05 232 查看
之前一直接触文件上传,以为文件下载是什么东西。仔细看了下,才发现其本质就是文件的复制。

下载的关键代码:

private void download(HttpServletRequest request,HttpServletResponse response) throws IOException {

File f = new File("c:\\095557357.jpg");

response.reset();
response.setContentType("image/jpeg");//设置下载文件的类型
response.setHeader("content-disposition","attachment; filename=text.jpg"); //设置下载的文件名

long fileLength=f.length();
String length1=String.valueOf(fileLength);
response.setHeader("Content_Length",length1); //下载文件的大小

InputStream in = new FileInputStream( f );
OutputStream out = response.getOutputStream();
byte[] buffer = new byte[2097152];

int ins = in.read(buffer);//读取字节到buffer中

//ins == -1 时 。就已经是文件的结尾了
while ( ins != -1 ) {
out.write(buffer, 0, ins);//将缓存buffer中的数据写到文件中
ins = in.read(buffer);
}
in.close();
out.flush();
out.close();
}


这是一个servlet,复制文件的代码。

response.setContentType("image/jpeg");


是比较重要的,标明本次下载的是一张图片。

发现之前想简单了,下载不仅仅是IO操作复制文件的。

struts2文件下载:

package com.download;

import java.io.*;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class Struts2DownloadAction extends ActionSupport {
/**
*
*/
private static final long serialVersionUID = 1L;
private String fileName;
private InputStream downloadFile;

public InputStream getDownloadFile(){
return downloadFile;
}
public String execute(){
System.out.println(fileName);
//downloadFile=new FileInputStream("H:\\apache-tomcat-6.0.43\\webapps\\struts2_1\\download\\"+fileName);
downloadFile=ServletActionContext.getServletContext().getResourceAsStream("download/"+fileName);
/**
* getResourceAsStream()方法只能使用相对路径,绝对路径会空值
* 如果执意使用绝对路径的话,就不使用该方法,直接使用新建InputStream对象
*/
return SUCCESS;
}

public void setFileName(String fileName) {
this.fileName = fileName;
}

public String getFileName() {
return fileName;
}
public void setDownloadFile(InputStream downloadFile) {
this.downloadFile = downloadFile;
}

}

<action name="strutsdownload" class="com.download.Struts2DownloadAction">
<result name="success" type="stream">
<param name="contentType">text/plain</param>
<param name="contentDisposition">attachment;fileName="${fileName}"</param>
<param name="inputName">downloadFile</param>
<param name="bufferSize">1024</param>
</result>
</action>
注意:

1.结果类型必须要写成 type="stream" ,与之对应的处理类是 org.apache.struts2.dispatcher.StreamResult

2:参数:

1) <param name="contentDisposition">attachment;fileName="${fileName}"</param>

contentDisposition默认是 inline(内联的), 比如说下载的文件是文本类型的,就直接在网页上打开,不能直接打开的才会打开下载框自己选择

2) attachment :下载时会打开下载框

3) fileName="${fileName}" :在这定义的名字是一个动态的,该名字是显示在下载框上的文件名字

3.<param name="inputName">downloadFile</param>,这个downloadFile名字要和FileDownload.java类中的getDownloadFile()方法名去掉get 一致

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'filedownload.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">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->

</head>

<body>
<h1>@选择文件进行下载</h1>
<table>
<tr>
<td>J2EE结构.png</td>
<td><a  href="<s:url value='strutsdownload'><s:param name='fileName'>J2EE结构.png </s:param></s:url>">下载</a>

</td>
</tr>
<tr>
<td>MVC图结构.png</td>
<td><a href="<s:url value='strutsdownload'><s:param name='fileName'>MVC图结构.png</s:param></s:url>">下载</a></td>
</tr>
<tr>
<td>JSPModel2.png</td>
<!-- <a>中的href写成这个样子是为了方便使用struts2的自动给参数赋值 -->
<td><a href="<s:url value='strutsdownload'><s:param name='fileName'>JSPModel2.png</s:param></s:url>">下载</a></td>
</tr>
</table>
</body>
</html>


java文件下载的几种方式:

public HttpServletResponse download(String path, HttpServletResponse response) {
try {
// path是指欲下载的文件的路径。
File file = new File(path);
// 取得文件名。
String filename = file.getName();
// 取得文件的后缀名。
String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

// 以流的形式下载文件。
InputStream fis = new BufferedInputStream(new FileInputStream(path));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
// 设置response的Header
response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
response.addHeader("Content-Length", "" + file.length());
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
toClient.write(buffer);
toClient.flush();
toClient.close();
} catch (IOException ex) {
ex.printStackTrace();
}
return response;
}

public void downloadLocal(HttpServletResponse response) throws FileNotFoundException {
// 下载本地文件
String fileName = "Operator.doc".toString(); // 文件的默认保存名
// 读到流中
InputStream inStream = new FileInputStream("c:/Operator.doc");// 文件的存放路径
// 设置输出的格式
response.reset();
response.setContentType("bin");
response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
// 循环取出流中的数据
byte[] b = new byte[100];
int len;
try {
while ((len = inStream.read(b)) > 0)
response.getOutputStream().write(b, 0, len);
inStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}

public void downloadNet(HttpServletResponse response) throws MalformedURLException {
// 下载网络文件
int bytesum = 0;
int byteread = 0;

URL url = new URL("windine.blogdriver.com/logo.gif");

try {
URLConnection conn = url.openConnection();
InputStream inStream = conn.getInputStream();
FileOutputStream fs = new FileOutputStream("c:/abc.gif");

byte[] buffer = new byte[1204];
int length;
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread;
System.out.println(bytesum);
fs.write(buffer, 0, byteread);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}


支持在线打开文件的一种方式:
public void downLoad(String filePath, HttpServletResponse response, boolean isOnLine) throws Exception {
File f = new File(filePath);
if (!f.exists()) {
response.sendError(404, "File not found!");
return;
}
BufferedInputStream br = 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());
// 文件名应该编码成UTF-8
} else { // 纯下载方式
response.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition", "attachment; filename=" + f.getName());
}
OutputStream out = response.getOutputStream();
while ((len = br.read(buf)) > 0)
out.write(buf, 0, len);
br.close();
out.close();
}


有点累了,不想深究,有时候再补充,先放一点别人那里copy的代码,以供不时之需。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: