码迷,mamicode.com
首页 > 编程语言 > 详细

FileDownLoad.java

时间:2017-12-05 13:31:14      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:direct   load   final   download   origin   redo   list   mkdir   tco   

package org.sujing.util;


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

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

public class FileDownLoad {

public static String download(String filepath,HttpServletRequest request, HttpServletResponse response) throws Exception{

BufferedInputStream bis = null;
BufferedOutputStream bos = null;
OutputStream fos = null;
InputStream fis = null;

/*//新建一个根路径(上传)
String path = request.getServletContext().getRealPath("upload_lujing");
//创建一个文件
File file1= new File(path+File.separator+file.getOriginalFilename());
//没有路径的时候创建一个路径
if(!file1.exists()){
file1.mkdirs();
}
//把file复制成file1
file.transferTo(file1);
//上传图片操作
empService.saveimg(id,"upload_lujing/"+file.getOriginalFilename());
//重定向到list.action
return "redirect:list.action";*/

try {
// 如果是从服务器上取就用这个获得系统的绝对路径方法。
//String filepath = request.getRealPath(filepatha);//方法过时了
String filepathall = request.getSession().getServletContext().getRealPath(filepath);

File uploadFile = new File(filepathall);

fis = new FileInputStream(uploadFile);
bis = new BufferedInputStream(fis);
fos = response.getOutputStream();
bos = new BufferedOutputStream(fos);

//得到文件名
String filename = filepath.substring(filepath.lastIndexOf("\\")+1);

// 这个就就是弹出下载对话框的关键代码
response.setHeader("Content-disposition", "attachment;filename="+ URLEncoder.encode(filename, "utf-8"));

int bytesRead = 0;
// 用输出流去写,缓冲输入输出流
byte[] buffer = new byte[8192];
while ((bytesRead = bis.read(buffer, 0, 8192)) != -1) {
bos.write(buffer, 0, bytesRead);
}

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NumberFormatException e) {
e.printStackTrace();
} finally {
try {
if (bos != null) {
bos.flush();
}
if (fis != null) {
fis.close();
}
if (bis != null) {
bis.close();
}
if (fos != null) {
fos.close();
}
if (bos != null) {
bos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}

FileDownLoad.java

标签:direct   load   final   download   origin   redo   list   mkdir   tco   

原文地址:http://www.cnblogs.com/supiaopiao/p/7986165.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!