gpt4 book ai didi

java - 如何设置客户端文件夹路径(如 D ://new folder) for download file in spring contoller?

转载 作者:行者123 更新时间:2023-11-28 23:59:45 24 4
gpt4 key购买 nike


我有一个spring controller,我想下载特定路径的文件,比如D://或K://,但现在默认会下载到downloads文件夹。
我正在从 /WEB-INF/文件夹(服务器端位于 Tomcat 文件夹中)获取我的文件,我想在客户端机器 D:\驱动器中写入,请看我下面的代码有问题请让我知道。我正在使用谷歌浏览器。
提前致谢

 public void downloadFile(HttpServletRequest request,
HttpServletResponse response) throws IOException {
//ServletContext context = request.getServletContext();
String filePath = request.getSession().getServletContext().getRealPath("/WEB-INF/") + "/"+"out.json";

// get absolute path of the application
ServletContext context = request.getServletContext();
String appPath = context.getRealPath("");
System.out.println("appPath = " + appPath);

// construct the complete absolute path of the file
//String fullPath = appPath + filePath;
File downloadFile = new File(filePath);
FileInputStream inputStream = new FileInputStream(downloadFile);

// get MIME type of the file
String mimeType = context.getMimeType(filePath);
if (mimeType == null) {
// set to binary type if MIME mapping not found
mimeType = "application/octet-stream";
}
System.out.println("MIME type: " + mimeType);

// set content attributes for the response
response.setContentType(mimeType);
response.setContentLength((int) downloadFile.length());

// set headers for the response
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"",
downloadFile.getName());
System.out.println("downloadFile.getName()" + downloadFile.getName());
response.setHeader(headerKey, headerValue);

// get output stream of the response
OutputStream outStream = response.getOutputStream();

byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;

// write bytes read from the input stream into the output stream
while ((bytesRead = inputStream.read(buffer)) != -1) {
outStream.write(buffer, 0, bytesRead);
}

inputStream.close();
outStream.close();
}

最佳答案

您无法决定客户端将下载的文件保存在服务器端的什么位置 - 事实上,您甚至无法影响它是否将它保存在任何地方!这是由客户端(例如 Chrome)决定的。

参见 Chrome help了解如何更改 Chrome 中的默认下载位置。

关于java - 如何设置客户端文件夹路径(如 D ://new folder) for download file in spring contoller?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33561455/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com