vue调用springboot项目下载文件
时间: 2023-08-10 15:20:22 浏览: 46
要在Vue中调用Spring Boot项目来下载文件,可以使用axios库来实现。首先,在Spring Boot中编写一个Controller,用于处理文件下载请求。例如:
```java
@GetMapping("/download")
public ResponseEntity<Resource> downloadFile(@RequestParam("filename") String filename) {
// Load file as Resource
Resource resource = fileService.loadFile(filename);
// Try to determine file's content type
String contentType = null;
try {
contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
} catch (IOException ex) {
logger.info("Could not determine file type.");
}
// Fallback to the default content type if type could not be determined
if (contentType == null) {
contentType = "application/octet-stream";
}
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType(contentType))
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
.body(resource);
}
```
在上面的Controller中,我们使用`fileService.loadFile(filename)`方法来加载要下载的文件,然后将其包装成一个`Resource`对象返回给前端。接下来,我们将文件的content type、文件名等信息设置到响应头中,并将文件内容作为响应体返回给前端。
在Vue中,我们可以使用axios库来发送下载文件的请求,例如:
```javascript
axios({
method: 'get',
url: '/api/download',
responseType: 'blob', // Important
}).then(response => {
const url = window.URL.createObjectURL(new Blob([response.data]))
const link = document.createElement('a')
link.href = url
link.setAttribute('download', 'file.pdf')
document.body.appendChild(link)
link.click()
})
```
在上面的代码中,我们设置`responseType`为`blob`,以便正确处理响应数据。然后,我们创建一个URL对象来将响应数据转换为URL,创建一个`<a>`标签来模拟用户点击下载链接,最后将标签添加到页面中并触发点击事件即可开始下载文件。