Toma im
Toma im

Reputation: 1

Save image to folder in project

Here is my code

public String addProducts() {
        try {
            filename = file.getSubmittedFileName();
            InputStream input;

            input = file.getInputStream();

            FileOutputStream output = new FileOutputStream("D:\\Driver\\"+filename);
            byte[] buf = new byte[1024];
            int len;
            while ((len = input.read(buf)) > 0) {
                output.write(buf, 0, len);
            }
            product.setImage(filename);
            productsFacade.create(product);
        } catch (IOException ex) {
            Logger.getLogger(ProductsMB.class.getName()).log(Level.SEVERE, null, ex);
        }
        return "products";
    }

Im not very familar with FileOutputStream, my code so far work but I don't know to change the path of FileOutputStream to save the file in my project folder (without specify which disk my project in)

There is also another way I tried like this

  ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        ServletContext servletContext = (ServletContext) externalContext.getContext();
        String uploadDirectory = servletContext.getRealPath("/resources/images/products");

        String filePath = uploadDirectory + "/" + filename;
        FileOutputStream output = new FileOutputStream(filePath);

Im makeing a enterprise application in netbeans here is where my folder tree

  -Web Pages
    -resources
     -images
      -products (where I want to save the file)
   -Source Package
    -com.mb
      -productsMB.java ( which my function is in)

Upvotes: 0

Views: 41

Answers (0)

Related Questions