简体   繁体   English

下载使用Java在服务器中创建的文件

[英]Downloading a file created in server using Java

I am trying to download a file from a given URL. 我正在尝试从给定的URL下载文件。 The URL is not a direct file URL. 该URL不是直接文件URL。 When this URL is provided in browser manually, we get a prompt for download/save. 在浏览器中手动提供此URL时,我们会提示您下载/保存。

For example, http://www.my-domain.com/download/type/salary/format/excel 例如, http://www.my-domain.com/download/type/salary/format/excel

I have no issues in the URL which has the file name directly in the URL. URL中没有问题,URL中直接包含文件名。 In the above URL, based on the format and type, server generates the file. 在上面的URL中,服务器根据格式和类型生成文件。

In Java I am trying to download the file using the below code. 在Java中,我尝试使用以下代码下载文件。 The file is created, but the content is just the domain content and not the actual excel data. 文件已创建,但内容仅是域内容,而不是实际的excel数据。

URL url = new URL("http://www.my-domain.com/download/type/salary/format/excel");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();

float totalDataRead = 0;
BufferedInputStream in = new BufferedInputStream(connection.getInputStream());
FileOutputStream fos = new FileOutputStream("c:\\test.xls");
BufferedOutputStream bout = new BufferedOutputStream(fos, 1024);

byte[] data = new byte[1024];
int i = 0;

while ((i = in.read(data, 0, 1024)) >= 0) {
    totalDataRead = totalDataRead + i;
    bout.write(data, 0, i);
}

bout.close();
in.close();

The content is whatever the server sent for that URL. 内容就是服务器为该URL发送的内容。 You can't do anything about that from the client end. 您不能从客户端对此做任何事情。 If it contained Javascript for example it won't get executed. 例如,如果包含Javascript,则将不会执行。

When you want to solve a problem you have to use the adequate tools to get the thing done. 当您要解决问题时,必须使用适当的工具来完成任务。 The adequate tools can be found at poi.apache.org. 足够的工具可以在poi.apache.org中找到。
Have a look at Apache POI . 看看Apache POI

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM