V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
sdenvi
V2EX  ›  编程

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

  •  
  •   sdenvi · 2016-08-18 17:43:37 +08:00 · 2902 次点击
    这是一个创建于 2779 天前的主题,其中的信息可能已经有所发展或是发生改变。

    文件能够正确的上传回显,但是下载的时候后台总是会报文件找不到的错误,(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);
    }
    
    4 条回复    2016-08-22 00:05:10 +08:00
    odirus
        1
    odirus  
       2016-08-18 18:03:18 +08:00
    https://commons.apache.org/proper/commons-io/javadocs/api-2.5/index.html

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

    https://en.wikipedia.org/wiki/HTTP_location
    odirus
        3
    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
        4
    Izual_Yang  
       2016-08-22 00:05:10 +08:00
    兰州不会一直这么写 url 吧
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3136 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 12:36 · PVG 20:36 · LAX 05:36 · JFK 08:36
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.