FileDownLoad.java

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了FileDownLoad.java相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章