以下是一个使用Angular和Spring Boot进行文件下载的示例:
Angular部分:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class FileDownloadService {
constructor(private http: HttpClient) { }
downloadFile(): Observable {
return this.http.get('http://localhost:8080/api/download', { responseType: 'blob' });
}
}
import { Component } from '@angular/core';
import { FileDownloadService } from './file-download.service';
@Component({
selector: 'app-root',
template: `
`
})
export class AppComponent {
constructor(private fileDownloadService: FileDownloadService) { }
downloadFile() {
this.fileDownloadService.downloadFile().subscribe(blob => {
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = 'file.pdf';
link.click();
});
}
}
Spring Boot部分:
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Path;
import java.nio.file.Paths;
@Controller
public class FileDownloadController {
@GetMapping("/api/download")
public ResponseEntity downloadFile() throws IOException {
String filename = "path/to/file.pdf";
Path filePath = Paths.get(filename);
Resource resource = new UrlResource(filePath.toUri());
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
.body(resource);
}
}
filename
变量中。请注意,这只是一个简单的示例,实际应用中可能需要进行更多的错误处理和安全性检查。