11

我想上传一张图片并将其存储在服务器上,然后用 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());

    }
}
4

2 回答 2

25

我想将它存储在应用程序的“资源/图像”中

不,请不要。WAR 部署空间不打算作为永久文件存储位置。每当您重新部署 webapp 时,所有这些上传的文件都会丢失,原因很简单,因为它们不包含在原始 WAR 中。另请参阅有关非常密切相关的问题的详细解释:Uploaded image only available after refresh the page


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

因为您在Part#write(). 它相对于您无法控制的当前工作目录。另请参阅此相关答案的详细说明:getResourceAsStream() vs FileInputStream。您需要指定绝对路径,换句话说,路径以/.


鉴于您使用的是 Glassfish,上传图片中的答案仅在刷新页面后可用,也应该为您完成。简而言之:

  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. 通过向webapp添加以下条目,告诉 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属性)

于 2013-10-02T16:47:36.287 回答
2

无法Path#write在 glassfish 中使用它,所以我使用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;
    }
于 2014-05-19T13:00:40.720 回答