java实现文件下载

有时候我们上传的图片等文件存入服务器中可以提供用户下载使用,这里主要使用流操作,我们依旧把重复性的代码封装到工具类中
一、定义工具类

package com.wwy.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * 下载文件的工具类
 * @author wwy
 * @date 2020年1月2日
 * @version v0.0.1
 *
 */
public class DownUtil {
public static void down(File file, HttpServletResponse response,HttpServletRequest request){	
	 FileInputStream in =null;
	 //创建输出流
	 OutputStream out = null;
	 try {
		 String filename = file.getName();
		 //获取下载标识
		 String mimeType = request.getServletContext().getMimeType(filename);
		 response.setContentType(mimeType);
		 response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(filename, "UTF-8"));
		 //如果文件不存在直接返回false
		 if(!file.exists()){
		     return;
		 }
			 in = new FileInputStream(file);
			 out = response.getOutputStream();
		 //缓存区
		 byte buffer[] = new byte[1024];
		 int length=0;
		 while ((length = in.read(buffer)) != -1) {  
			    out.write(buffer, 0, length);  
			    out.flush();
			} 
		}catch(Exception e) {
			 e.printStackTrace();
			 throw new RuntimeException();
			 //关流
		 }finally {
			 try {
				out.close();
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}finally {
				out=null;
				in=null;
			}
		 }
}
}

二、业务代码
这里只做简单的演示,省去了权限验证和查询真实路径的过程

package com.wwy.test.down;

import java.io.File;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.wwy.entry.APIEntry;
import com.wwy.util.DownUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping("down")
@Api(tags = "文件下载")
public class DownController {
	
	
	@PostMapping("get")
	@ApiOperation("下载")
public APIEntry get( HttpServletResponse response,HttpServletRequest request,String filepath) {
	//1.判断用户权限
	//2.根据前端传递的filepath(回显的虚拟地址)查询真实文件路径
	//这里只做测试,直接把path写死,也不做权限的验证
		filepath="D:\\upload\\2019\\12\\16\\40692af5391c419a88f88b655cbe91de.png";
		File file=new File(filepath);
		DownUtil.down(file, response, request);
		
		return APIEntry.OK(null);
}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值