@GetMapping("/getTemplateFile")
@ApiOperation("数据模板下载")
public ResponseEntity<byte[]> downFile(HttpServletRequest request) throws IOException {
File file = new File("C/AA");
filename = getFilename(request, filename);
HttpHeaders headers = new HttpHeaders();
headers.setContentDispositionFormData("attachment", filename);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity<>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK);
* 根据浏览器的不同进行编码设置
* @param request 请求对象
* @param filename 需要转码的文件名
* @return 返回编码后的文件名
* @throws IOException
public String getFilename(HttpServletRequest request, String filename) throws IOException {
String[] IEBrowserKeyWords = {"MSIE", "Trident", "Edge"};
String userAgent = request.getHeader("User-Agent");
for (String keyWord : IEBrowserKeyWords) {
if (userAgent.contains(keyWord)) {
return URLEncoder.encode(filename, "UTF-8");
return new String(filename.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
@GetMapping("/getTemplateFile") @ApiOperation("数据模板下载") public ResponseEntity<byte[]> downFile(HttpServletRequest request) throws IOException { File file = new File("C/AA"); filename = getFilename(request, filename); ...
在 Spring Boot 中下载文件有以下几种方式:
通过 ResponseEntity 将文件以二进制流的形式返回给客户端。优点是可以自定义文件名和响应头,缺点是需要手动读取文件并返回。
通过 ServletContext 将文件作为静态资源返回给客户端。优点是简单易用,缺点是不能自定义文件名和响应头。
通过 Apache 的 FileUtils 工具类将文件作为附件返回给客户端。优点是可以...
String content = contents;
Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); // 指定编码...
private static void downLoadExcel( String fileName, HttpServletResponse response,
Workbook workbook) {
try {
response.setCharacterEncoding(“UTF-8”);
response.setHeader(“content-Type”, “multipart/form-data”);
response.setHeader(“Content-Disposition”,
“attac
- 使用@RequestBody接收byte[];
- 通过字节流OutputStream生成二进制文件;
- Postman构造请求时,在Body体中使用二进制形式发送byte[];
- RestTemplate携带byte[]时使用ByteArrayResource作为HttpEntity类型。
// 路由注解可添加consumes参数指定Content-Type类型,如application/octet-stream
@PostMapping(value = "/test")
public void testBinary(HttpServletRequest request) throws IOException {
File targetFile = new File("d:/test333.png");
ServletInputStre...
在Spring Boot中,可以使用JPA或MyBatis等ORM框架来操作MySQL数据库。对于存储的二进制文件,可以使用byte[]类型来存储,然后在需要还原的地方将其从数据库中读取出来。
下面是一个示例:
1. 创建一个实体类来映射数据库中的表:
```java
@Entity
@Table(name = "file")
public class FileEntity {
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String fileName;
private byte[] content;
// getter and setter
2. 在Service层中定义一个方法来获取二进制文件:
```java
@Service
public class FileService {
@Autowired
private FileRepository fileRepository;
public byte[] getFileContent(Long fileId) {
return fileRepository.findById(fileId)
.orElseThrow(() -> new RuntimeException("File not found"))
.getContent();
3. 在Controller层中定义一个接口来返回二进制文件:
```java
@RestController
public class FileController {
@Autowired
private FileService fileService;
@GetMapping("/file/{id}")
public ResponseEntity<byte[]> getFile(@PathVariable Long id) {
byte[] content = fileService.getFileContent(id);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", "file.bin");
return new ResponseEntity<>(content, headers, HttpStatus.OK);
4. 在Vue中,可以使用axios来调用上述接口:
```javascript
axios({
method: 'get',
url: '/file/' + fileId,
responseType: 'blob'
}).then(response => {
const blob = new Blob([response.data]);
const url = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'file.bin');
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
5. 在Element UI中,可以使用el-button来触发上述逻辑:
```html
<template>
<el-button @click="downloadFile">Download File</el-button>
</template>
<script>
import axios from 'axios';
export default {
name: 'DownloadFile',
data() {
return {
fileId: 1
methods: {
downloadFile() {
axios({
method: 'get',
url: '/file/' + this.fileId,
responseType: 'blob'
}).then(response => {
const blob = new Blob([response.data]);
const url = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'file.bin');
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
</script>