gpt4 book ai didi

java - 通过part.write将带有httpservlet的文件上传到java.io.tmpdir - 到绝对tmp路径

转载 作者:行者123 更新时间:2023-12-01 13:02:05 25 4
gpt4 key购买 nike

我正在尝试制作一个 servlet 将文件上传到临时位置。当我构建文件路径时,一切似乎都正常。

String uploadFilePath = System.getProperty("java.io.tmpdir") + File.separator + UPLOAD_DIR;

我得到绝对路径:C:\Users\victor\AppData\Local\Temp\uploads

但是当我打电话

part.write(uploadFilePath + File.separator + fileName);

我得到:C:\Users\victor\GlassFish_Server\glassfish\domains\domain\generated\jsp\pcpweb\C:\Users\victor\AppData\Local\Temp\uploads

然后是一个 java.io.FileNotFoundException ,我想已经足够了。

所以“写”正在完成我的道路。我有办法避免这种情况吗?谢谢。

使用:glassfish 和 netbeans

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");

// constructs path of the directory to save uploaded file
String uploadFilePath = System.getProperty("java.io.tmpdir") + File.separator + UPLOAD_DIR;

// creates the save directory if it does not exists
File fileSaveDir = new File(uploadFilePath);
if (!fileSaveDir.exists()) {
fileSaveDir.mkdirs();
}
System.out.println("Upload File Directory=" + fileSaveDir.getAbsolutePath());

String fileName = null;
//Get all the parts from request and write it to the file on server
for (Part part : request.getParts()) {
fileName = getFileName(part);
part.write(uploadFilePath + File.separator + fileName);
}

request.setAttribute("message", fileName + " File uploaded successfully!");
getServletContext().getRequestDispatcher("gerencia.jsp").forward(
request, response);
}

最佳答案

Part.write() 的 javadoc 提到:

The file is created relative to the location as specified in the MultipartConfig

我的理解是,对于Glassfish,如果不指定位置,则默认为:

getServletContext().getAttribute("javax.servlet.context.tempdir")

这可能是您看到的额外路径。

尝试在@MultipartConfig注释中指定位置,例如:

@MultipartConfig(location="/somepath")

您可以将位置设置为临时目录的值,然后将裸文件名传递给 write() 方法。

关于java - 通过part.write将带有httpservlet的文件上传到java.io.tmpdir - 到绝对tmp路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23449995/

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