用于上传的Servlet抛出FileNotFoundException

时间:2015-11-10 00:39:17

标签: java servlets

我有一个像这样的servlet:

import java.io.File;
import java.io.IOException;
import java.util.List;  
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

@WebServlet(name = "ServletUpload", urlPatterns = {"/ServletUpload"})
@MultipartConfig
public class ServletUpload extends HttpServlet {

    private File uploadFolder;

    @Override
    public void init() throws ServletException {
        uploadFolder = new File("C:/Users/athos36848/Git/smartlist/smartlist-utfpr-code/Smartlist/web/");
    }

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        String caminho_arquivo = "";
      //process only if its multipart content
        if (ServletFileUpload.isMultipartContent(request)){
            try {
                List<FileItem> multiparts = new ServletFileUpload(
                                         new DiskFileItemFactory()).parseRequest(request);
                for (FileItem item : multiparts){
                    if (!item.isFormField()){
                        String contentType = item.getContentType();
                       // if (!contentType.equals("image/png") && (!contentType.equals("image/jpeg"))) {
                            File uploadDir = new File(uploadFolder + "imagens" + File.separator);                         
                            File file = new File(uploadDir + File.separator);
                            String name = new File(item.getName()).getName();
                            item.write(new File(file + File.separator + name));
                            caminho_arquivo = file + File.separator + name;
                            request.setAttribute("sucesso", "Cadastro feito com sucesso!");
                     //   } else {
                     //       request.setAttribute("sucesso", "Apenas PNG ou JPG são suportados!");
                     //   }
                    }
                }         
            } catch (Exception ex) {
               System.out.println(ex);
               request.setAttribute("sucesso", "Ocorreu um erro! Mensagem para o administrador: " + ex);
            }          
        } else {
            request.setAttribute("sucesso",
                                 "Você abriu essa URL por engano.");
        }
        System.out.println(caminho_arquivo);
        request.getRequestDispatcher("WEB-INF/sucesso.jsp").forward(request, response);
    }

当我尝试通过表单上传时,它会抛出FileNotFoundException

Informações:   java.io.FileNotFoundException: C:\Users\athos36848\Git\smartlist\smartlist-utfpr-code\Smartlist\webimagens\1446617374_227_CircledList.png (O sistema não pode encontrar o caminho especificado)
    at java.io.FileOutputStream.open0(Native Method)
    at java.io.FileOutputStream.open(FileOutputStream.java:270)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:162)
    at org.apache.commons.fileupload.disk.DiskFileItem.write(DiskFileItem.java:417)
    at org.smartlist.Controller.ServletUpload.processRequest(ServletUpload.java:46)
    at org.smartlist.Controller.ServletUpload.doPost(ServletUpload.java:92)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
    ...

为什么会这样?它位于项目文件夹中,因此应用程序应该有权在其上书写。

编辑:放弃该代码,并从标记的问题中尝试另一个代码。它看起来像这样:

   @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Part filePart = request.getPart("file"); // Retrieves <input type="file" name="file">
        String fileName = filePart.getSubmittedFileName();
        String contentType = filePart.getContentType();
        System.out.println(contentType);
        if (!contentType.equals("image/png") && !contentType.equals("image/jpeg")) {
            request.setAttribute("titulo", "Ops!");
            request.setAttribute("sucesso", "Apenas PNG e JPG são suportados!");
            request.getRequestDispatcher("sucesso.jsp").forward(request, response);
        } else {
            File uploads = new File("C:\\imgSmartList");
            File file = new File(uploads, fileName);
            try (InputStream input = filePart.getInputStream()) {
               Files.copy(input, file.toPath());
               request.setAttribute("titulo", "Ops!");
               request.setAttribute("sucesso", "Upload feito com sucesso!");
            } catch (Exception e) {
               request.setAttribute("titulo", "Ops!");
               request.setAttribute("sucesso", "Algo de errado aconteceu! Mensagem pro administrador: \n" + e);
            }
            request.getRequestDispatcher("sucesso.jsp").forward(request, response);
        }
    }

1 个答案:

答案 0 :(得分:2)

更改

 File uploadDir = new File(uploadFolder + "imagens" + File.separator);  

File uploadDir = new File(uploadFolder + File.separator + "imagens");

File uploadDir = new File(uploadFolder, "imagens");

参考:http://docs.oracle.com/javase/7/docs/api/java/io/File.html

public File(String pathname)

通过将给定的路径名​​字符串转换为抽象路径名来创建新的File实例。如果给定的字符串是空字符串,则结果是空的抽象路径名。即使您将其写入文件路径,它也不会包含'/'。

public File(File parent,String child)

从父路径名字符串和子路径名字符串创建新的File实例。这是我认为你需要的确切功能。