Загрузка файла в веб-приложение Java показывает, что файл не найден, исключение

Я разрабатываю веб-приложение с использованием jsp и сервлетов. Я пытаюсь загрузить файл, а затем обрабатываю данные этого файла. для этой цели мой код 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>

Сервлет Java с именем "LoadFile.java" содержит следующий код в методе 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. Что мне нужно сделать?


person Qazi    schedule 29.06.2015    source источник
comment
Кто выбрасывает это исключение? Конструктор FileOutputStream?   -  person sp00m    schedule 29.06.2015
comment
Пожалуйста, дайте нам точную трассировку стека FNFE   -  person Buurman    schedule 29.06.2015
comment
Отображается сообщение об отказе в доступе   -  person Qazi    schedule 29.06.2015


Ответы (1)


В папке вашего веб-приложения WEB-INF создайте папку с именем files и измените код FileOutputStream, как показано ниже.

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