前端实现下载pdf功能
vue点击下载,下载pdf
图片展示
前端代码
//下载
downloadFile(){
let params = { //参数列表
path: this.fileName
};
var Axios = axios.create({
timeout: 3600 * 1000
});
//添加请求拦截器
Axios.interceptors.request.use(
function (config) {
// 在发送请求之前处理
// header头添加token
config.headers['authc-token'] = window.localStorage.token;
return config;
},
function (error) {
// 发送请求错误处理
return Promise.reject(error);
}
);
let url = "请求接口"
Axios.post(url, params, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, responseType: "blob" }).then(res => {
const link = document.createElement("a");
let blob = new Blob([res.data], { type: "application/pdf" }); //类型excel
link.style.display = "none";
link.href = URL.createObjectURL(blob);
link.setAttribute("download", this.fileName);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}).catch(res => {
console.log(res);
});
},
后端代码
Controller层
/**
* 下载接口,传入一个路径就可以了
* @param request
* @param response
* @return
*/
@RequestMapping(value = "/download", method = RequestMethod.POST)
public byte[] download(HttpServletRequest request, HttpServletResponse response) {
byte[] bytes = null;
try{
//将传入参数转换为JSONObject,这里是我自己写记的,换成自己的
JSONObject requestJson = JsonUtil.httpParameterToJSONObject(request);
bytes = pdfService.downFile(requestJson);
}catch (Exception e){
e.printStackTrace();
}
return bytes;
}
interface接口
/**
* 前端下载文件
* @param jsonObject
* @return
*/
byte[] downFile(JSONObject jsonObject);
service层
@Override
public byte[] downFile(JSONObject jsonObject) {
byte[] bytes = null;
try{
//传过来的文件名
String path = jsonObject.getString("path");
File file = new File("自己的文件路径"+path);
bytes = DownloadFile.File2byte(file);
}catch (Exception e){
logger.error("PdfServiceImpl——>downFile——>下载pdf异常",e.fillInStackTrace());
}
return bytes;
}
DownloadFile类
/**
* 将文件转换成byte数组
* @param filePath 文件File类 通过new File(文件路径)
* @return byte数组
*/
public static byte[] File2byte(File filePath) {
byte[] buffer = null;
try {
FileInputStream fis = new FileInputStream(filePath);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
fis.close();
bos.close();
buffer = bos.toByteArray();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return buffer;
}