我正在尝试使用 JAVA NIO 将文件从主机 A 传输到客户端 B,而无需在本地下载文件,然后为客户端 B 提供下载文件的链接。
我正在运行 spark Apache 框架并使用 maven 项目。
我使用以下方法在 Spark 中映射了请求http://localhost:8080/download/hello:get("/download/:id",RequestHandler::downloadHandler);
函数内部是从以下位置下载文件的代码:“ https://download.springsource.com/release/STS/3.8.1.RELEASE/dist/e4.6/spring-tool-suite-3.8.1.发布-e4.6-linux-gtk-x86_64.tar.gz "
try {
URL url = new URL("https://download.springsource.com/release/STS/3.8.1.RELEASE/dist/e4.6/spring-tool-suite-3.8.1.RELEASE-e4.6-linux-gtk-x86_64.tar.gz");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
int respCode = +httpURLConnection.getResponseCode();
System.out.println("response code : "+respCode);
if (respCode == HttpURLConnection.HTTP_OK){
String fileName = "";
String disposition = httpURLConnection.getHeaderField("Content-Disposition");
String contentType = httpURLConnection.getContentType();
int contentLength = httpURLConnection.getContentLength();
if (disposition != null) {
// extracts file name from header field
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10,
disposition.length() - 1);
}
} else {
// extracts file name from URL
fileName = url.toString().substring(url.toString().lastIndexOf("/") + 1,
url.toString().length());
}
System.out.println("Content-Type = " + contentType);
System.out.println("Content-Disposition = " + disposition);
System.out.println("Content-Length = " + contentLength);
System.out.println("fileName = " + fileName);
httpURLConnection.disconnect();
System.out.println("other stuff : ");
System.out.println(url.getHost());
ReadableByteChannel readableByteChannel = Channels.newChannel(url.openStream());
FileOutputStream fileOutputStream = new FileOutputStream(fileName);
FileChannel fileChannel = fileOutputStream.getChannel();
fileChannel.transferFrom(readableByteChannel, 0, Long.MAX_VALUE);
fileOutputStream.close();
readableByteChannel.close();
}
} catch (IOException e) {
e.printStackTrace();
}
我使用 httpURLConnection 获取文件名和文件大小,然后进行处理以下载文件。我想要做的是,而不是使用fileChannel.transferFrom(readableByteChannel, 0, Long.MAX_VALUE)
将文件直接传输到客户端来在本地下载文件。
我做了一些研究,我认为使用 Socketchannels 是可能的,但我不明白它应该如何工作。
我还阅读了这篇文章 https://examples.javacodegeeks.com/core-java/nio/java-nio-large-file-transfer-tutorial/ 并试图了解 Reciever 类,但我仍然不清楚如何.
我会很感激一些指导。谢谢