How to write a file to resource/images folder of the app?

前端 未结 2 1844
离开以前
离开以前 2020-11-28 06:58

I would like to upload an image and store it on the server, and later to show it with h:graphicImage? I would like to store it in \"resources/images\" of the app. I am using

2条回答
  •  庸人自扰
    2020-11-28 07:23

    Wasn't able to get it working with Path#write in glassfish, so I used Path#getInputStream as follows:

    public void upload(){
            BufferedInputStream bis = null;
            BufferedOutputStream bos = null;
            try {
                String filename = getFilename(uploadedFile);
                File file = new File("/var/webapp/images/"+filename);
                bis = new BufferedInputStream(uploadedFile.getInputStream());
                FileOutputStream fos = new FileOutputStream(file);
                bos = new BufferedOutputStream(fos);
                int x;
                while((x = bis.read())!= -1){
                    bos.write(x);
                }
            } catch (IOException ex) {
                Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
            }
            finally{
                try {
                    bos.flush();
                    bos.close();
                    bis.close();
                } catch (IOException ex) {
                    Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    
    private static String getFilename(Part part) {
            for (String cd : part.getHeader("content-disposition").split(";")) {
                if (cd.trim().startsWith("filename")) {
                    String filename = cd.substring(cd.indexOf('=') + 1).trim().replace("\"", "");
                    return filename.substring(filename.lastIndexOf('/') + 1).substring(filename.lastIndexOf('\\') + 1); // MSIE fix.
                }
            }
            return null;
        }
    

提交回复
热议问题