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

小编典典

对我来说,建议的文件名存储在头文件Content-Disposition中:

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

我正在从nexus下载文件,因此对于不同的服务器/应用程序,它可能存储在不同的标头字段中,但是很容易通过诸如firebug的firebug之类的工具来查找。

以下几行对我来说很好

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();

}

2020-06-16


版权声明:本文为weixin_29144945原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。