【问题标题】:how to download zip-file from client machine instead of opening file in browser using java?如何从客户端机器下载 zip 文件,而不是使用 java 在浏览器中打开文件?
【发布时间】:2014-10-11 06:40:48
【问题描述】:

下面给出的用于将文件下载到客户端机器的代码。我正在尝试使用 java servlet 将文件下载到客户端计算机。但它没有下载我在控制台检查但没有发生错误

试试{

                FileInputStream fileInputStream = new FileInputStream(downloadPath);
                response.setContentType("application/zip");
                response.setHeader("Content-Disposition", "attachment; filename=\""+dndfilename);
                response.setContentLength(fileInputStream.available());
                int i;
                while ((i = fileInputStream.read()) != -1) {
                    response.getOutputStream().write(i);
//                  System.out.println("Result: " +i);
                }
                response.getOutputStream().flush();
                response.getOutputStream().close();
                fileInputStream.close();

            } catch (IOException e) {
                e.printStackTrace();
            }

【问题讨论】:

  • 此代码下载客户端机器。 客户端获取文件称为上传。请说明您要执行的操作。注意您不必设置内容长度,并且使用available() 不是一种有效的方法。
  • @EJP 实际上我正在尝试将文件从服务器下载到客户端,而不是在浏览器中打开下载文件
  • 好吧,只要它真的是一个 zip 文件,它应该可以工作。摆脱内容长度行。
  • @EJP 是的,只有它的 zip 文件
  • “不工作”没有传达任何有用的信息。

标签: java servlets download zip


【解决方案1】:
Actually i send the request in ajax so only it's not working after that i change the request.




 var serverURL = hURL + "/rup";
            var parameters = "requestType=port&subRequestType=portScen&userName=" + userName + "&scen=" + selectedScen;
            $.ajax({
                type: "POST",
                data: parameters,
                url: serverURL,
                cache:false,
                dataType:"html",
                success: function() {
                    updateStatusMessage("success", "Scen port successfully");
                },
                async:false
            });

Solution of the problem:

var serverURL = hURL + "/rpp?requestType=port&subRequestType=portScen&userName=" + userName + "&scen=" + selectedScen;
window.open(serverURL, '_blank');

【讨论】:

    【解决方案2】:

    使用 out.write 并将字节流中的文件传递给 out.write。它会保存文件而不是打开

    【讨论】:

      猜你喜欢
      • 2011-11-08
      • 2019-03-08
      • 1970-01-01
      • 2011-10-18
      • 2016-12-14
      • 2012-06-14
      • 2013-10-25
      • 1970-01-01
      相关资源
      最近更新 更多