DownloadController层
package com.xc.project.controller;
import com.xc.project.common.ErrorCode;
import com.xc.project.exception.BusinessException;
import com.xc.project.service.UserService;
import com.xc.xcapicommon.model.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.nio.file.Files;
/**
* @author xc
* @date 2023/4/19 15:35
*/
@RestController
@Slf4j
@RequestMapping("download")
public class DownloadController {
@Autowired
private UserService userService;
// 文件下载在服务器路径,因为我这只有一个文件,所以这么写,实际可以根据访问路径来匹配资源
private static final String SDK_HELP_ADDRESS = "/home/XC/download/xcapi-client-sdk.zip";
@GetMapping("sdkHelp")
public ResponseEntity downloadSdkHelp(HttpServletRequest request) throws IOException {
// 请求不能为null
if (request == null) {
throw new BusinessException(ErrorCode.FORBIDDEN_ERROR);
}
// 当前登录用户要存在
User loginUser = userService.getLoginUser(request);
if (loginUser == null || loginUser.getId() == null) {
throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
}
//获取要下载的文件
File file = new File(SDK_HELP_ADDRESS);
InputStream is = Files.newInputStream(file.toPath());
//获取文件输入流
//创建资源对象,将输入流加载其中
InputStreamResource resource = new InputStreamResource(is);
//设置响应头,指定文件名称
HttpHeaders headers = new HttpHeaders();
// 只有设置正确的响应头,客户端才知道此时是文件下载
headers.add("Content-Disposition", String.format("attachment; filename=%s", file.getName()));
//返回文件下载响应
return ResponseEntity.ok().headers(headers).contentLength(file.length()).body(resource);
}
}
前端react页面
import {PageContainer,} from '@ant-design/pro-components';
import {
Button,
Descriptions, Form,
} from 'antd';
import {
getEncryptUsingGET,
} from "@/services/xcapi-backend/userController";
import {useState} from "react";
import {decrypt} from "@/utils/ComplexEncryption";
/**
* SDK调用帮助页面
* @constructor
*/
const Index: React.FC = () => {
const loadData = async () => {
const {data} = await getEncryptUsingGET();
return data;
}
let [encryptAk, setEncryptAk] = useState('');
let [encryptSk, setEncryptSk] = useState('');
loadData().then(data => {
console.log(data?.encryptAk)
setEncryptAk(decrypt(data?.encryptAk));
setEncryptSk(decrypt(data?.encryptSk));
})
return (
{}
{encryptAk}
{encryptSk}
// 通过button的href来下载服务器的压缩包
>
);
};
export default Index;
服务器托管,北京服务器托管,服务器租用 http://www.fwqtg.net
机房租用,北京机房租用,IDC机房托管, http://www.fwqtg.net
相关推荐: SpringCloud网关——GateWay
GateWayGateWay 本专栏学习内容来自尚硅谷周阳老师的视频 有兴趣的小伙伴可以点击视频地址观看 概述 SpringCloud Gateway 是 Spring Cloud 的一个全新项目,基于 Spring 5.0+Spring Boot 2.0 和 Projec…