文件下载(已修改)

package cn.download;


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;


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


public class DisposeDownload extends HttpServlet {
//下载内容
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset = utf-8");
OutputStream out = response.getOutputStream();
//如果是get方式提交
String fileName = request.getParameter("filename");
fileName = new String(fileName.getBytes("ISO-8859-1"),"utf-8");

//截取老文件名
String oldFileName = fileName.split("_")[0];
//得到存文件的路径
String storePath = getServletContext().getRealPath("/WEB-INF/file");
//得到文件的全部路径
String filePath = makeStorePath(storePath, fileName)+"\\"+fileName;

//判断文件是否存在
File file = new File(filePath);
System.out.println(file);
if(!file.exists()){
out.write("对比起!你要下载的文件可能已经不存在了".getBytes("UTF-8"));
return ;
}

InputStream in = new FileInputStream(file);
//通知客服端一下载方式打开(为了防止下载的内容是中文 ,所以用一下方式)
response.setHeader("Content-Disposition", "attachment;filename = "+URLEncoder.encode(oldFileName,"utf-8"));

byte[] b = new byte[1024];
int len = -1;
while((len = in.read(b))!=-1){
out.write(b, 0, len);
}
}


private String makeStorePath(String storePath, String fileName) {
int hashCode = fileName.hashCode();
//得到两个文件夹
int dir1 = hashCode & 0xf; // 0000~1111:整数0~15共16个
int dir2 = (hashCode & 0xf0) >> 4; // 0000~1111:整数0~15共16个


String path = storePath;// + "\\" + dir1 ; // WEB-INF/files/12
File file = new File(path);
if (!file.exists())
//创建一个文件夹
file.mkdirs();
return path;
}


public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);


}


}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值