如何将文件写入应用程序的资源/图像文件夹?

时间:2013-10-02 14:28:38

标签: jsf file-upload glassfish jsf-2.2

我想上传一张图片并将其存储在服务器上,然后用h:graphicImage显示它?我想将它存储在应用程序的“资源/图像”中。我正在使用glassfish 4.现在,文件转到“domain1 \ generated \ jsp \ FileUpload”。谢谢

我的表格

<h:form id="form" enctype="multipart/form-data">
        <h:messages/>
        <h:panelGrid columns="2">
            <h:outputText value="File:"/>
            <h:inputFile id="file" value="#{uploadPage.uploadedFile}"/>
        </h:panelGrid>
        <br/><br/>
        <h:commandButton value="Upload File" action="#{uploadPage.uploadFile}"/>
</h:form>

我的豆子

@Named
@ViewScoped
public class UploadPage {       
    private Part uploadedFile; 

    public void uploadFile(){
       File file = File.createTempFile("somefilename-", ".jpg", new File("C:\\var\\webapp\\images"));
    uploadedFile.write(file.getAbsolutePath());

    }
}

2 个答案:

答案 0 :(得分:23)

  

我想将其存储在应用

的“资源/图片”中

不,请不要。 WAR部署空间不是永久文件存储位置。每当您重新部署Web应用程序时,所有这些上载的文件都会丢失,原因很简单,因为它们不包含在原始WAR中。有关一个非常密切相关的问题的答案,请参阅详细解释:Uploaded image only available after refreshing the page


  

现在,文件转到“domain1 \ generated \ _jsp \ FileUpload”。

因为您在Part#write()中指定了相对路径。它变得相对于您无法控制的当前工作目录。请参阅相关答案:getResourceAsStream() vs FileInputStream。您需要指定绝对路径,换句话说,使用/启动路径。


鉴于你正在使用Glassfish,Uploaded image only available after refreshing the page中的答案也应该为你做。简而言之:

  1. 创建/var/webapp/images文件夹。请注意,此路径仅供参考,完全免费供您选择。另请注意,当您使用带有C:\磁盘的Windows时,此路径等同于C:\var\webapp\images

  2. 将上传的文件保存在那里。

    Path file = Files.createTempFile(Paths.get("/var/webapp/images"), "somefilename-", ".jpg", );
    
    try (InputStream input = uploadedFile.getInputStream()) {
        Files.copy(input, file, StandardCopyOption.REPLACE_EXISTING);
    }
    
    imageFileName = file.getFileName().toString();
    // ...
    

    (注意:Files#createTempFile()用于自动生成唯一的文件名,否则当新上传的文件(巧合)具有完全相同的文件名时,先前上传的文件将被覆盖)

  3. 告诉GlassFish在/var/webapp/images注册虚拟主机,以便http://example.com/images上的所有文件都可以通过将以下条目添加到网络应用的/WEB-INF/glassfish-web.xml来获取:

    <property name="alternatedocroot_1" value="from=/images/* dir=/var/webapp" />
    

    (注意:alternatedocroot_1必须完全相同,保持不变,如果您有多个,请将其命名为alternatedocroot_2等;另请注意/images部分应该确实不包含在dir属性中,这不是拼写错误)

  4. 现在您可以按如下方式显示它:

    <h:graphicImage value="/images/#{bean.imageFileName}" />
    

    (注意:使用value属性,而不是name属性)

答案 1 :(得分:1)

无法在glassfish中使用Path#write,因此我使用了Path#getInputStream,如下所示:

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