作者在 2019-03-23 15:47:30 发布以下内容
//通过服务端
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
public void down(String fileId,HttpServletResponse response) {
//文件路径存在db中
String path = "D:/test/1.xlsx";
File file = new File(path);
//创建文件输入流
try {
FileInputStream in = new FileInputStream(file);
} catch (IOException e) {
e.printStackTrace();
}
//创建输出流
OutputStream out = null;
try {
out = response.getOutputStream();
response.reset();
String fileSuffix = null;
if(null != path||path.length!=0){
fileSuffix=path.substring(path.lastIndexOf(".")+1);
}
response.setContentType(fileSuffix);
String fileName = path.substring(path.lastIndexOf("\\")+1);
response.setHeader("Content-Disposition", "attachment;filename="+fileName);
} catch (IOException e) {
e.printStackTrace();
}
downloadFile(file, out);
}
public void downloadFile(File file, OutputStream output){
FileInputStream fileInputStream = null;
BufferedInputStream inputStream = null;
try {
fileInputStream = new FileInputStream(file);
inputStream = new BufferedInputStream(fileInputStream);
byte[] buffer = new byte[8192];//1024*8
int i;
while ((i = inputStream.read(buffer)) != -1) {
output.write(buffer,0,i);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (inputStream != null)
inputStream.close();
if (fileInputStream != null)
fileInputStream.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}