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