java 将 Web 应用程序中的文件上传到项目根文件夹

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12961041/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 10:58:40  来源:igfitidea点击:

Upload file in web application to project root folder

javatomcatweb-applicationsfile-uploaddirectory

提问by Carel

I am currently working on a web application. In some part of this application I want to upload files to a certain directory. Initially, when I wrote my test cases this worked perfectly:

我目前正在开发一个 Web 应用程序。在此应用程序的某些部分,我想将文件上传到某个目录。最初,当我编写测试用例时,这非常有效:

final static String IMAGE_RESOURCE_PATH = "res/images";

...

File directory = new File(IMAGE_RESOURCE_PATH + "/" + productId);

if(!directory.exists()) {
    directory.mkdirs();
}

This creates the directory wherein the file will be uploaded. The resulting path will be:

这将创建将上传文件的目录。结果路径将是:

[project root folder]/res/images/[productId]

[项目根文件夹]/res/images/[productId]

Since deploying the application to a server (Tomcat 7), the directory gets created in the root of the IDE I'm using, which is a bit confusing to me.

由于将应用程序部署到服务器 (Tomcat 7),因此在我使用的 IDE 的根目录中创建了该目录,这让我有点困惑。

eg: C:\Eclipse86\res\images

例如:C:\Eclipse86\res\images

Any idea how I can revert back to the project path with just plain Java without using some hacked technique or hard-coding the path?

知道如何在不使用某些黑客技术或对路径进行硬编码的情况下仅使用普通 Java 恢复到项目路径吗?

回答by Artem Shafranov

If you don't specify the absolute path, your directory will be created inside (or, if correctly, relative to) working directory of the application.

如果您不指定绝对路径,您的目录将在应用程序的工作目录中(或者,如果正确,相对于)创建。

If you want to get directory inside your web application you should use getServletContext().getRealPath(String path). For example, getServletContext().getRealPath("/")is the path to the root directory of the application.

如果你想在你的 web 应用程序中获取目录,你应该使用getServletContext().getRealPath(String path). 例如,getServletContext().getRealPath("/")是应用程序根目录的路径。

To create directory with path [project root folder]/res/images/[productId], do something like this:

要使用 path 创建目录[project root folder]/res/images/[productId],请执行以下操作:

// XXX Notice the slash before "res"
final static String IMAGE_RESOURCE_PATH = "/res/images";

...

String directoryPath = 
        getServletContext().getRealPath(IMAGE_RESOURCE_PATH + "/" + productId)
File directory = new File(directoryPath);

if(!directory.exists()) {
    directory.mkdirs();
}

回答by user

Some years ago I wrote a servlet that DOWNloads a file. You could quickly refactor it for uploading. Here you go:

几年前,我写了一个下载文件的 servlet。您可以快速重构它以进行上传。干得好:

public class ServletDownload extends HttpServlet {

    private static final int BYTES_DOWNLOAD = 1024;  
    public void doGet(HttpServletRequest request, 

    HttpServletResponse response) throws IOException {
        response.setContentType("text/plain");
        response.setHeader("Content-Disposition", "attachment;filename=downloadname.txt");
        ServletContext ctx = getServletContext();
        InputStream is = ctx.getResourceAsStream("/downloadme.txt");

        int read = 0;
        byte[] bytes = new byte[BYTES_DOWNLOAD];
        OutputStream os = response.getOutputStream();

        while((read = is.read(bytes))!= -1) {
            os.write(bytes, 0, read);
        }
        os.flush();
        os.close(); 
    }
}

Also, there is an easy way to get the projects' path, as new File().getAbsolutePath().

此外,还有一种获取项目路径的简单方法,如 new File().getAbsolutePath()。