[英]How to get the original file name when downloading file with java
當我用這樣的URL
從URL
下載文件時,如何獲取原始文件名
File file = new File( "test" ) ;
FileUtils.copyURLToFile(URL, file)
因為當我創建文件時我必須放一個名字,但在這個階段我還不知道下載文件的原始名稱。
對我來說,建議的文件名存儲在頭文件Content-Disposition中:
Content-Disposition: attachment; filename="suggestion.zip"
我正在從nexus下載文件,因此對於不同的服務器/應用程序,它可能存儲在不同的頭字段中,但很容易找到一些工具,如firebug for firefox。
以下幾行對我來說很好
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.