java实现文件下载

下载的流程如下:
客户端请求资源,服务器根据客户端传过来的参数,找到资源响应。

详细代码如下:
download.jsp:
<%@ 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>Insert title here</title>
</head>
<body>
  <form action="http://localhost:8080/myupload/FileDownloadServlet"

ENCTYPE="multipart/form-data" METHOD="GET">
    <input type="hidden" name="fileName" id="fileName" value="uploadFile

\Image1391826552379.jpg">
    <input type="submit" value="下载">
  </form>
</body>
</html>

java后台代码:

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class FileDownloadServlet
 */
public class FileDownloadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FileDownloadServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse

response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {
       doPost(request,response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse

response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {
    
    
        String fileName=request.getParameter("fileName");
        if(fileName==null){
            fileName="";
        }
        fileName=fileName.trim();
        InputStream inStream=null;
        String attchName="";
        
        byte[] b=new byte[100];
        int len=0;
        
        attchName=getAttchName(fileName);//取得附件名称
        fileName=getRealName(request,fileName);//取得附件的全路径
        
        if(fileName==null){
            System.out.println("文件不存在,或者禁止下载");
            return;
        }
        attchName=tuUtf8String(attchName);//将文件转码utf-8
        inStream=new FileInputStream(fileName);
        response.reset();//必须reset,否则会出现文件不完整
        response.setContentType("application/x-msdownload");
        response.addHeader("Content-Disposition","attachment; filename=\""+

attchName + "\"");
        //循环取出流中的数据
        while((len=inStream.read(b))>0){
            response.getOutputStream().write(b,0,len);
        }
        inStream.close();
     }

    private String tuUtf8String(String attchName) {
        StringBuffer sb=new StringBuffer();
        for(int i=0;i<attchName.length();i++){
            char c=attchName.charAt(i);
            if(c>=0&&c<255){
                sb.append(c);
            }else{
                byte[] b;
                try {
                    b=Character.toString(c).getBytes("utf-8");
                } catch (UnsupportedEncodingException e) {
                    System.out.println(e.getMessage());
                    b=new byte[0];
                }
                for(int j=0;j<b.length;j++){
                    int k=b[j];
                    if(k<0)
                        k+=256;
                    sb.append("%"+Integer.toHexString(k).toUpperCase

());
                }
            }
        }
        String sUtf8=sb.toString();
        sb.delete(0,sb.length());
        sb.setLength(0);
        sb=null;
        return sUtf8;
    }

    @SuppressWarnings({ "deprecation", "unused" })
    private String getRealName(HttpServletRequest request, String fileName) {
   
        String path="C:\\";//也可以给定一个域名地址(专门提供下载服务),这样主服

务器压力就不会那么大
        if(request==null||fileName==null){
            return null;
        }
        fileName=fileName.trim();
        if(fileName.equals("")){
            return null;
        }
        String filePath=path+fileName;
        if(filePath==null){
            return null;
        }
        File file=new File(filePath);
        if(!file.exists()){
            return null;
        }
        return filePath;
    }

    private String getAttchName(String fileName) {
        if(fileName==null){
            return "";
        }
        fileName=fileName.trim();
        int pos=0;
        
        pos=fileName.lastIndexOf("\\");
        if(pos>-1){
            fileName=fileName.substring(pos+1);
        }
        pos=fileName.lastIndexOf("/");
        if(pos>-1){
            fileName=fileName.substring(pos+1);
        }
        pos=fileName.lastIndexOf(File.separator);
        if(pos>-1){
            fileName=fileName.substring(pos+1);
        }
        return fileName;
    }

}

值得留意的是服务器的根据客户端的传回来的相对地址,来找到资源的方式。一般的响应资源的服务

器不会放在跟主服务器同一主机上。


效果图:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值