[DEBUG] Spring boot前端html无法下载示例文件

更新:原方法打jar包的时候是可以的,后来我打war包之后下载的文件就是0字节。尴尬:)

所以现在更换一种方法,然后打war包。在服务器已测试成功。

前端不需要改变,只需要更改controller:

    @RequestMapping("/example")
    @ResponseBody
	public void downloadExampleFileForUser(HttpServletResponse response) throws Exception {
		String filePath = "/static/example.txt";
		String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
		downloadExampleFile(response, filePath, fileName);
		return;
	}
    
    private void downloadExampleFile(HttpServletResponse response, String path, String name) throws IOException {
    	response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(name, "UTF-8"));
    	response.setContentType("content-type:octet-stream");
        // FileUploadController是当前文件的名称
    	InputStream inputStream =FileUploadController.class.getResourceAsStream(path);
    	OutputStream outputStream = response.getOutputStream();
    	byte[] buffer = new byte[1024];
    	int len;
    	while ((len = inputStream.read(buffer)) != -1) {
    		outputStream.write(buffer, 0, len);
    	}
    	inputStream.close();
    	outputStream.close();
    }

然后把要下载的文件,example.txt放在static下

 =======================================================================

我只想在前端给一个示例文件example.zip供下载!静态的,一般不改变。

在html中写下载链接,但是始终报无法下载。

已经尝试过:

1.把example.zip拷贝在resources根目录下和templates下

2。前端删掉href或者download都不对

<a id="example_file" href="example.zip" download="example.zip" >Example File</a>

网上有一种思路是重写输出,但是我懒,所以用了简单点的方法。

============================================================================

把example.zip放在templates下

html修改:

<a id="example_file" th:href="@{/example}" download="example.zip" >Example File</a>

controller修改

@RequestMapping("/example")
public String downloadExampleFile(HttpServletRequest request, HttpServletResponse response) {
	String fileName = "example.zip";
	//System.out.println();
	File file = new File(fileName);
	if (file.exists()) {
	  System.out.println(file.getParent());
	}
	return null;
}

其实啥都没做。。。。就是给了个映射==

===============================================

我是Ruriko,我爱这个世界:)

原文地址:https://www.cnblogs.com/pxy7896/p/11542419.html