帮我写一段java代码 实现前后端使用ajax请求下载文件
时间: 2024-05-02 09:19:17 浏览: 17
好的,以下是实现前后端使用ajax请求下载文件的Java代码:
前端代码(使用 jQuery ajax):
```javascript
function downloadFile() {
$.ajax({
url: "/download",
type: "GET",
xhrFields: {
responseType: 'blob'
},
success: function(result) {
var a = document.createElement('a');
var blob = new Blob([result], { type: 'application/octet-stream' });
var url = window.URL.createObjectURL(blob);
a.href = url;
a.download = "file.xlsx";
a.click();
window.URL.revokeObjectURL(url);
}
});
}
```
后端代码(使用 Spring MVC):
```java
@RequestMapping(value = "/download", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<byte[]> downloadFile() throws IOException {
//读取文件到byte数组
FileInputStream input = new FileInputStream(new File("file.xlsx"));
byte[] bytes = IOUtils.toByteArray(input);
//设置header,让浏览器弹出下载对话框
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", "file.xlsx");
//返回响应对象
return new ResponseEntity<>(bytes, headers, HttpStatus.OK);
}
```
希望对您有帮助!
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)