0

I have a servlet like this:

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);
    }

When I try to make an upload through an form, it throws a 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)
    ...

Why this happen? It is on the project folder, so the application should have rights to write on it.

Edit: Gave up on that code and tried another one from the marked question. It looks like this:

   @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);
        }
    }
athosbr99
  • 463
  • 2
  • 7
  • 24

1 Answers1

2

change

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

to

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

or to

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

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

public File(String pathname)

Creates a new File instance by converting the given pathname string into an abstract pathname. If the given string is the empty string, then the result is the empty abstract pathname. It will not include '/' in it, even if you write it into the File path.

public File(File parent,String child)

Creates a new File instance from a parent pathname string and a child pathname string. This is the exact func you need I think.

Harper Koo
  • 597
  • 5
  • 14