有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java web应用程序中的jsp文件上载显示未找到文件异常

我正在使用jsp和servlet开发一个web应用程序。我试图上传一个文件,然后处理该文件的数据。为此,我的jsp代码是

<form action="LoadFile" method="post" enctype="multipart/form-data" accept-charset="UTF-8">
     <input type="file" name="file" id="file" size="50" accept=".doc, .docx, .txt"/>
     <br />
     <input type="submit" value="Check Now" name="upload" id="upload"/>
</form>

名为“LoadFile.Java”的Javaservlet在processRequest方法中包含以下代码

request.setCharacterEncoding("UTF-8");
        Part filePart = request.getPart("file");
        String fileName = getFileName(filePart);

        OutputStream outStream = null;
        InputStream filecontent = null;
        final PrintWriter writer = response.getWriter();

        try {
            outStream = new FileOutputStream(new File(File.separator
                    + fileName));

            filecontent = filePart.getInputStream();

            int read = 0;
            final byte[] bytes = new byte[1024];

            while ((read = filecontent.read(bytes)) != -1) {
                outStream.write(bytes, 0, read);
            }
            writer.println("New file " + fileName + " created at " + filePath);
        } catch (FileNotFoundException fne) {
            writer.println("You either did not specify a file to upload or are "
                    + "trying to upload a file to a protected or nonexistent "
                    + "location.");
            writer.println("<br/> ERROR: " + fne.getMessage());

        }

每当我尝试上载文件时,它都会给出FileNotFoundExceptin。 我需要做什么


共 (1) 个答案

  1. # 1 楼答案

    在Web应用程序WEB-INF文件夹中创建一个名为files的文件夹,并按如下所示更改FileOutputStream的代码

    outStream = new FileOutputStream(new File(request.getRealPath("/WEB-INF/")+ "files"+ File.separator
                        + fileName));