java 下载文件的问题,太纠结了

2016-08-18 17:43:37 +08:00
 sdenvi

文件能够正确的上传回显,但是下载的时候后台总是会报文件找不到的错误,(http:\localhost:80\gms\upload\123456.xlsx (文件名、目录名或卷标语法不正确。))但是这个路径直接贴到浏览器里面是可以下载到的,下载的代码如下:

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	try {
		request.setCharacterEncoding("UTF-8");
		String downFilename = request.getParameter("curfile");
		String filepath = request.getParameter("path");
		response.setContentType("text/plain");
		response.setHeader("Location", downFilename);
		response.setHeader("Content-Disposition", "attachment; filename=" + downFilename);
		OutputStream outputStream = response.getOutputStream();
		InputStream inputStream = new FileInputStream(filepath);
		byte[] buffer = new byte[1024];
		int i = -1;
		while ((i = inputStream.read(buffer)) != -1) {
			outputStream.write(buffer, 0, i);
		}
		outputStream.flush();
		outputStream.close();
	} catch (FileNotFoundException e1) {
		e1.printStackTrace();
		System.out.println("没有找到您要的文件");
	} catch (Exception e) {
		e.printStackTrace();
		System.out.println("系统错误,请及时与管理员联系");
	}
}

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	doPost(request, response);
}
2922 次点击
所在节点    编程
4 条回复
odirus
2016-08-18 18:03:18 +08:00
https://commons.apache.org/proper/commons-io/javadocs/api-2.5/index.html

copyURLToFile 用了这个函数,整个世界都安静了。
hcymk2
2016-08-18 18:03:33 +08:00
没见过这样写文件下载的
你这是 2 种方式混着写的吧。

https://en.wikipedia.org/wiki/HTTP_location
odirus
2016-08-18 18:06:21 +08:00
另外你这个地址 http:\localhost:80\gms\upload\123456.xlsx

换成 http://localhost:80\gms\upload\123456.xlsx 试试

还不行的话再试试 http://127.0.0.1:80\gms\upload\123456.xlsx

现在的浏览器都很智能,一些常见的 URL 错误能够给你自动纠正,但你的程序科没那么聪明哦
Izual_Yang
2016-08-22 00:05:10 +08:00
兰州不会一直这么写 url 吧

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/300229

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX