简体   繁体   English

使用java下载文件时如何获取原始文件名

[英]How to get the original file name when downloading file with java

How to get original file name when i download file from URL with java like this 当我用这样的URLURL下载文件时,如何获取原始文件名

File file = new File( "test" ) ;
FileUtils.copyURLToFile(URL, file)

Because when i create file i must put a name but at this stage i don't know yet the original name of downloading file. 因为当我创建文件时我必须放一个名字,但在这个阶段我还不知道下载文件的原始名称。

For me the suggested file name is stored in the header file Content-Disposition: 对我来说,建议的文件名存储在头文件Content-Disposition中:

Content-Disposition: attachment; filename="suggestion.zip"

I am downloading a file from nexus, so for different servers/applications it might be stored in a different header field but it is easy to find out with some tools like firebug for firefox. 我正在从nexus下载文件,因此对于不同的服务器/应用程序,它可能存储在不同的头字段中,但很容易找到一些工具,如firebug for firefox。

The following lines work fine for me 以下几行对我来说很好

URL url = new URL(urlString);
// open the connection
URLConnection con = url.openConnection();
// get and verify the header field
String fieldValue = con.getHeaderField("Content-Disposition");
if (fieldValue == null || ! fieldValue.contains("filename=\"")) {
  // no file name there -> throw exception ...
}
// parse the file name from the header field
String filename = fieldValue.substring(fieldValue.indexOf("filename=\"") + 10, fieldValue.length() - 1);
// create file in systems temporary directory
File download = new File(System.getProperty("java.io.tmpdir"), filename);

// open the stream and download
ReadableByteChannel rbc = Channels.newChannel(con.getInputStream());
FileOutputStream fos = new FileOutputStream(download);
try {
  fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
} finally {
  fos.close();
}

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

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