JAVA下载文件

//通过服务端
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;
Java
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);
	       }./*欢迎加入java交流Q君样:909038429一起吹水聊天
	  } catch (IOException e) {
	            e.printStackTrace();
	  } finally {
	       try {
	            if (inputStream != null)
	                inputStream.close();
	            if (fileInputStream != null)
	                fileInputStream.close();
	       }catch (IOException e) {
	                e.printStackTrace();
	       }
	  }

}

image
最新2020整理收集的一些高频面试题(都整理成文档),有很多干货,包含mysql,netty,spring,线程,spring cloud、jvm、源码、算法等详细讲解,也有详细的学习规划图,面试题整理等,需要获取这些内容的朋友请加Q君样:909038429
/./*欢迎加入java交流Q君样:909038429一起吹水聊天

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值