Java 使用vue和spring下载excel文件
我正在尝试使用spring(Java)创建一个excel文件,然后将其发送到Vue,以便使用web浏览器下载该文件 我使用Java服务创建了excel文件,但我不知道如何以及必须返回VueJava 使用vue和spring下载excel文件,java,excel,vue.js,axios,Java,Excel,Vue.js,Axios,我正在尝试使用spring(Java)创建一个excel文件,然后将其发送到Vue,以便使用web浏览器下载该文件 我使用Java服务创建了excel文件,但我不知道如何以及必须返回Vue @RequestMapping(value = "/getmathresume", method = RequestMethod.GET) public FileOutputStream getMathResume() { //Long code with XSSFWorkbook(); //.
@RequestMapping(value = "/getmathresume", method = RequestMethod.GET)
public FileOutputStream getMathResume()
{
//Long code with XSSFWorkbook();
//.
//.
//.
// Finally I Write the output to a file, but I don't want to save it locally, instead, the idea
// is send it to Front and download the file with the Browser.
try {
FileOutputStream fileOut = new FileOutputStream("poi-generated-file.xlsx");
workbook.write(fileOut);
fileOut.close();
workbook.close();
}catch (FileNotFoundException e) {
System.out.println(e);
} catch (IOException e) {
e.printStackTrace();
}
//Using the code from the accepted answer
try {
File file = new File("poi-generated-file.xlsx");
Files.copy(file.toPath(), response.getOutputStream());
String mimeType = URLConnection.guessContentTypeFromName(file.getName());
String contentDisposition = String.format("attachment; filename=%s", file.getName());
int fileSize = Long.valueOf(file.length()).intValue();
response.setContentType(mimeType);
response.setHeader("Content-Disposition", contentDisposition);
response.setContentLength(fileSize);
}catch (FileNotFoundException e) {
System.out.println(e);
} catch (IOException e) {
e.printStackTrace();
}
}
__________________________VUE代码____________________________
getMathResume()
{
axios({
url: 'http://localhost:8081/user/getmathresume',
method: 'GET',
responseType: 'blob',
}).then((response) => {
var fileURL = window.URL.createObjectURL(new Blob([response.data]));
var fileLink = document.createElement('a');
fileLink.href = fileURL;
fileLink.setAttribute('download', 'matematica.xlsx');
document.body.appendChild(fileLink);
fileLink.click();
});
},
我不认为这是一件很难做到的事情,但我找不到这样的教程。
希望有人能帮我
编辑:添加了新的工作代码。在发送到客户端之前是否需要将其保存为文件?当我将工作簿写入字节数组并发送到客户端时,它似乎不起作用。。。。
@RequestMapping(value = "/getmathresume", method = RequestMethod.GET)
public void getMathResume(HttpServletResponse response) {
try {
File file = new File("poi-generated-file.xlsx");
Files.copy(file.toPath(), response.getOutputStream());
String mimeType = URLConnection.guessContentTypeFromName(file.getName());
String contentDisposition = String.format("attachment; filename=%s", file.getName());
int fileSize = Long.valueOf(file.length()).intValue();
response.setContentType(mimeType);
response.setHeader("Content-Disposition", contentDisposition);
response.setContentLength(fileSize);
}catch (FileNotFoundException e) {
System.out.println(e);
} catch (IOException e) {
e.printStackTrace();
}
}