使用HTTP方式下载文件( 仅支持另存为)

public class DownFile extends HttpServlet{

@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

// TODO Auto-generated method stub

resp.setContentType("text/html;charset=utf-8");

resp.setCharacterEncoding("utf-8");

resp.reset();

long pos = 0;

String fileLocation = req.getParameter("fileName");

System.out.println("The file is:" + fileLocation);

String subFileName = fileLocation.substring(fileLocation.lastIndexOf("/")+1,fileLocation.length());

String fileName = new String(subFileName.getBytes("iso-8859-1"),"utf-8");

OutputStream os = null;

FileInputStream is = null;

try {

File f = new File(req.getSession().getServletContext().getRealPath("/resource/temp/down") +"/"+fileName);

is = new FileInputStream(f);

long fSize = f.length();

byte xx[] = new byte[4096];

resp.setHeader("Accept-Ranges", "bytes");

resp.setHeader("Content-Length", fSize + "");

//对名字进行编码,这一步很重要

String encoderName = URLEncoder.encode(fileName, "UTF-8");

//filename下载时显示的文件名

resp.setHeader("Content-Disposition", "attachment;filename="+encoderName);

if (req.getHeader("Range") != null) {

// 若客户端传来Range,说明之前下载了一部分,设置206状态(SC_PARTIAL_CONTENT)

resp.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);

pos = Long.parseLong(req.getHeader("Range").replaceAll("bytes=", "").replaceAll("-", ""));

}

if (pos != 0) {

String contentRange = new StringBuffer("bytes ")

.append(new Long(pos).toString()).append("-")

.append(new Long(fSize - 1).toString()).append("/")

.append(new Long(fSize).toString()).toString();

resp.setHeader("Content-Range", contentRange);

System.out.println("Content-Range=" + contentRange);

// 略过已经传输过的字节

is.skip(pos);

}

os = resp.getOutputStream();

boolean all = false;

while (!all) {

int n = is.read(xx);

if (n != -1) {

os.write(xx, 0, n);

} else {

all = true;

}

}

} catch (IOException e) {

e.printStackTrace();

return;

} finally {

if (is != null)

is.close();

if (os != null)

os.close();

}

}


@Override

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {



}


}


----------------------------------------------------------------------------------------------

jsp页面


<a href="<%=path %>/downFile?fileName=${content.filePath}">下载</a>


以下方法也可使用

在服务器端把文件转换成输出流,写入到response,以response把文件带到浏览器,由浏览器来提示用户是否愿意保存文件到本地

--------------------------

第一种:

下载页面

<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<html>
 <head> 
 <title>download</title>

 </head> 
 <body>
 <a href="xia.jsp?filename=新建文档.txt">新建文档.txt</a>
 </body>
</html>

然后编写如下页面

<%@ page contentType="text/html;charset=gbk"%>
<%@ page language="java" import="java.io.*,java.net.*" pageEncoding="gbk"%>
<html>
 <head> 
 <title>test</title>

 </head> 
 <body>
<% 
 response.setContentType("text/html");
 javax.servlet.ServletOutputStream ou = response.getOutputStream();
 String filepath="uploadfile/";
 String filename=new String(request.getParameter("filename").getBytes("ISO8859_1"),"GB2312").toString();
 System.out.println("DownloadFile filepath:" + filepath);
 System.out.println("DownloadFile filename:" + filename);
 java.io.File file = new java.io.File(filepath + filename);
 if (!file.exists()) {
 System.out.println(file.getAbsolutePath() + " 文件不存在!");
 return;
 }
 // 读取文件流
 java.io.FileInputStream fileInputStream = new java.io.FileInputStream(file);
 // 下载文件
 // 设置响应头和下载保存的文件名
 if (filename != null && filename.length() > 0) {
 response.setContentType("application/x-msdownload");
 response.setHeader("Content-Disposition", "attachment; filename=" + new String(filename.getBytes("gb2312"),"iso8859-1") + "");
 if (fileInputStream != null) {
 int filelen = fileInputStream.available();
 //文件太大时内存不能一次读出,要循环
 byte a[] = new byte[filelen];
 fileInputStream.read(a);
 ou.write(a);
 }
 fileInputStream.close();
 ou.close();
 }
%> 
 </body>
</html>

第二种方法

使用servlet 首先配置web.xml

 <servlet>
 <servlet-name>DownloadFile</servlet-name>
 <servlet-class>com.servlet.DownloadFile</servlet-class>
 </servlet>

 <servlet-mapping>
 <servlet-name>DownloadFile</servlet-name>
 <url-pattern>/downloadfile</url-pattern>
 </servlet-mapping>

编写DownloadFile.java类

package libin123.com.cn.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.sun.image.codec.jpeg.ImageFormatException;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageDecoder;

public class DownloadFile extends HttpServlet {

 private static final long serialVersionUID = 1L;

 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 response.setContentType("text/html");
 javax.servlet.ServletOutputStream out = response.getOutputStream();

//得到下载的路径
 String filepath=request.getRealPath("/") + "uploadfile/";
 String filename=new String(request.getParameter("filename").getBytes("ISO8859_1"),"GB2312").toString();
 System.out.println("DownloadFile filepath:" + filepath);
 System.out.println("DownloadFile filename:" + filename);
 java.io.File file = new java.io.File(filepath + filename);
 if (!file.exists()) {
 System.out.println(file.getAbsolutePath() + " 文件不存在!");
 return;
 }
 // 读取文件流
 java.io.FileInputStream fileInputStream = new java.io.FileInputStream(file);
 // 下载文件
 // 设置响应头和下载保存的文件名
 if (filename != null && filename.length() > 0) {
 response.setContentType("application/x-msdownload");
 response.setHeader("Content-Disposition", "attachment; filename=" + new String(filename.getBytes("gb2312"),"iso8859-1") + "");
 if (fileInputStream != null) {
 int filelen = fileInputStream.available();
 //文件太大时内存不能一次读出,要循环
 byte a[] = new byte[filelen];
 fileInputStream.read(a);
 out.write(a);
 }
 fileInputStream.close();
 out.close();
 }
 }

 public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 response.setContentType("text/html");
 PrintWriter out = response.getWriter();
 out.println("<!DOCTYPE HTML PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN>");
 out.println("<HTML>");
 out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
 out.println(" <BODY>");
 out.print(" This is ");
 out.print(this.getClass().getName());
 out.println(", using the POST method");
 out.println(" </BODY>");
 out.println("</HTML>");
 out.flush();
 out.close();
 } 
}

下载页面

<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<html>
 <head>

 </head> 
 <body>
 <a href="downloadfile?filename=新建文档.txt">新建文档.txt</a>
 </body>
</html>

http://www.eshow365.cn

 

你可能感兴趣的:(java,urldecode,urlencode)