2015-01-09 46 views
0

我的想法是上傳一張圖片,並根據需要用ajax多次更新div(包含圖片)。我想這樣做是因爲我使用了一個視圖範圍管理bean。我刷新(f5)視圖但從未使用ajax時獲得成功。在部分ajax提交中重新加載圖形?

上面的代碼就像一個嚮導,首先我上傳一張圖片,第二張我剪切圖片,第三張我顯示按鈕來保存裁剪圖像或重新上傳新圖片,然後重新開始或重新拍攝原始圖片。

我使用JSF 2.2,PF 5,彈簧4和SWF 2.4

我第一次通過嚮導獲得作品的權利,即使我用AJAX更新顯示的畫面,但是當我再次使用嚮導,然後新的圖片被省略並查看顯示舊圖片。

  <h:panelGroup layout="block" id="finalConfigurationContainer" styleClass="finalConfigurationContainer"> 
      <h1> 
       <h:outputText value="#{msg['configuration1.main.header']}" /> 
      </h1> 

      <h:outputText value="#{msg['configuration1.main.msg']}" /> 


      <h:panelGroup layout="block" id="addSpaceImgContainer" styleClass="addSpaceImgContainer"> 
       <h:form> 
        <h:inputHidden value="#{pictureProvider.idRequest}" /> 
       </h:form> 


       <h:form id="uploadForm" rendered="#{pictureProvider.flagPicture}" enctype="multipart/form-data" prependId="false"> 
         <p:fileUpload allowTypes="/(\.|\/)(jpe?g)$/" cancelLabel="#{msg['upload.cancel.msg']}" dragDropSupport="true" fileLimit="1" 
          fileLimitMessage="#{msg['upload.filelimit.msg']}" fileUploadListener="#{pictureProvider.handFile}" 
          invalidFileMessage="#{msg['upload.invalidfile.msg']}" invalidSizeMessage="#{msg['upload.invalidsize.msg']}" 
          label="#{msg['upload.label.msg']}" sizeLimit="5242880" mode="advanced" uploadLabel="#{msg['upload.upload.msg']}" 
          update="@all" /> 

        <h:panelGroup layout="block" id="previewPictureContainer" rendered="#{selectedSpace.img or pictureProvider.flagPreviewPicture}" styleClass="previewPictureContainer"> 
         <h:outputText value="#{msg['configuration1.preview.msg']}" /> 

         <p:graphicImage cache="false" value="#{request.requestURL.substring(0, request.requestURL.length() - request.requestURI.length())}#{request.contextPath}/images/#{selectedSpace.idSpace}/coverPicture.jpeg" /> 

         <h:commandButton action="recrop" value="#{msg['reuse.btn']}" alt="#{msg['reuse.btn.alt']}" title="#{msg['reuse.btn.title']}" accesskey="4" /> 
        </h:panelGroup> 
       </h:form> 
      </h:panelGroup> 

      <h:panelGroup layout="block" id="cropperSpaceImgContainer" styleClass="cropperSpaceImgContainer"> 
       <h:form id="cropperForm" rendered="#{pictureProvider.flagCropper}" prependId="false"> 
        <h:panelGroup layout="block" id="preRenderSpaceImgContainer" styleClass="preRenderSpaceImgContainer"> 
         <p:imageCropper immediate="true" initialCoords="225,75,300,75" widgetVar="casas" value="#{pictureProvider.croppedImage}" image="#{request.requestURL.substring(0, request.requestURL.length() - request.requestURI.length())}#{request.contextPath}/images/#{selectedSpace.idSpace}/coverPicture.jpeg" alt="#{msg['cropper.picture.msg']}" /> 

        </h:panelGroup> 

        <h:panelGroup layout="block" id="croppedButtonsContainer" styleClass="croppedButtonsContainer"> 
         <p:commandButton update="@all" value="#{msg['crop.btn']}" action="#{pictureProvider.crop}" icon="ui-icon-scissors"/>      
        </h:panelGroup> 
       </h:form> 
      </h:panelGroup> 

      <h:panelGroup layout="block" id="saveCropImgContainer" styleClass="saveCropImgContainer"> 
       <h:form id="controlForm" rendered="#{pictureProvider.flagSave}" prependId="false"> 
        <h:panelGroup layout="block" id="renderSpaceImgContainer" styleClass="renderSpaceImgContainer"> 
         <p:graphicImage cache="false" value="#{request.requestURL.substring(0, request.requestURL.length() - request.requestURI.length())}#{request.contextPath}/images/#{selectedSpace.idSpace}/tempCrop.jpeg" /> 
        </h:panelGroup> 

        <h:panelGroup layout="block" id="saveCropButtonsContainer" styleClass="saveCropButtonsContainer"> 
         <p:commandButton update="@all" value="#{msg['crop.btn']}" action="recrop" alt="#{msg['crop.btn.alt']}" title="#{msg['crop.btn.title']}" icon="ui-icon-scissors"/> 
         <p:commandButton update="@all" value="#{msg['save.crop.btn']}" action="#{pictureProvider.save(flowRequestContext)}" alt="#{msg['save.crop.btn.alt']}" title="#{msg['save.crop.btn.title']}" /> 
         <p:commandButton update="@all" value="#{msg['reupload.btn']}" action="reupload" alt="#{msg['reupload.btn.alt']}" title="#{msg['reupload.btn.title']}" /> 
        </h:panelGroup> 
       </h:form> 
      </h:panelGroup> 

      <h:panelGroup layout="block" id="omit1StepContainer" styleClass="omit1StepContainer"> 
       <h:form prependId="false"> 
        <p:commandButton value="#{msg['omit.btn']}" action="omitPicture" alt="#{msg['omit.btn.alt']}" title="#{msg['omit.btn.title']}" accesskey="10" /> 
       </h:form> 
      </h:panelGroup> 
     </h:panelGroup> 

豆代碼

@Component("pictureProvider") 
@Scope("view") 
public class PictureProvider implements Serializable { 


@Autowired 
private ServletContext sc; 

@Autowired 
private ISpaceBO spaceBo; 

public void handFile(FileUploadEvent event){ 
    logger.entry("PictureProvider.handFile()"); 

    String pathMultimedia=sc.getInitParameter("multimediaPath"); 

    RequestContext requestContext=RequestContextHolder.getRequestContext(); 
    Space space=(Space)requestContext.getFlowScope().get("selectedSpace"); 

    RequestControlContext rec = (RequestControlContext) requestContext; 



    //Create multimedia folder 
    File f=new File(pathMultimedia + File.separator + space.getIdSpace()); 

    if(f.exists()){ 
     logger.debug("Multimedia folder already exist"); 

     try{ 
      savePicture(event,f,this.getIdRequest(),space.getIdSpace()); 
     }catch (FacesException e){ 
      //return "error"; 
     } 

    }else{ 

     //0777 permissions 
     f.setReadable(true, false); 
     f.setWritable(true, false); 
     f.setExecutable(true,false); 

     if(f.mkdir()){ 
      logger.debug("Multimedia folder was created"); 

      try{ 
       savePicture(event,f,this.getIdRequest(),space.getIdSpace()); 
      }catch (FacesException e){ 
       //Arreglar 
       //return "error"; 
      } 
     }else{ 
      //Arreglar 
      //return "error"; 
     } 
    } 

    //Redirecting to transition, it's necessary to reload cropper 
    //rec.handleEvent(new Event(this,"yes")); 

    event=null; 
} 

public void savePicture(FileUploadEvent upload,File file,String idRequest,Integer idSpace){ 
    logger.entry("PictureProvider.savePicture()"); 

    InputStream data; 
    byte[] bytes=null; 

    try { 
     data = upload.getFile().getInputstream(); 
     bytes=IOUtils.toByteArray(data); 
    } catch (IOException e1) { 
     // TODO Auto-generated catch block 
     e1.printStackTrace(); 
    } 

    String extension=upload.getFile().getContentType().replace("image/",""); 
    extension="." + extension; 

    FileImageOutputStream imageOutput=null; 
    String namePic=null; 
    try{ 

     switch (idRequest) { 
      case "event": 
       String nameEventFolder="E" 
         + spaceBo.getDao().countSectionPages(idSpace,4); 
       File f=new File(file.getAbsolutePath() + 
         File.separator + "events" + File.separator + nameEventFolder); 

       if(f.exists()){ 
        int totalFiles=f.listFiles().length; 
        namePic="pic_" + totalFiles + extension; 

        imageOutput=new FileImageOutputStream(new File(f.getAbsolutePath() 
          + File.separator + namePic)); 
       }else{ 
        f.setExecutable(true,false); 
        f.setWritable(true, false); 
        f.setReadable(true, false); 

        if(f.mkdirs()){ 
         int totalFiles=f.listFiles().length; 
         namePic="pic_" + totalFiles + extension; 

         imageOutput=new FileImageOutputStream(new File(f.getAbsolutePath() 
          + File.separator + namePic)); 
        } 
       } 

       RequestContext requestContext=RequestContextHolder.getRequestContext(); 
       EventProvider eventProviderBean=(EventProvider) requestContext.getActiveFlow() 
                   .getApplicationContext().getBean("eventProvider"); 

       //eventProviderBean.setTempFolderName(nameEventFolder); 
       eventProviderBean.getTempPicNames().add(namePic.substring(0, namePic.indexOf("."))); 


       //MARCAR ERRORES si no es un DIRECTORIO 
       break; 

      case "configuration": 
       imageOutput=new FileImageOutputStream(new File(file.getAbsolutePath() + 
         File.separator + "coverPicture" + extension)); 
      default: 
       break; 
     } 

     if(imageOutput!=null){ 
      imageOutput.write(bytes,0,bytes.length); 
      imageOutput.close(); 

      this.setFlagPicture(false); 
      this.setFlagCropper(true); 
      this.setFlagPreviewPicture(true); 
     } 


    }catch(Exception e) { 
      throw new FacesException("Error writing multimedia data"); 
    } 

} 

public void crop(){ 
    logger.entry("PictureProvider.crop()"); 

    if(getCroppedImage()==null){ 
     return; 
    } 

    String filename=getCroppedImage().getOriginalFilename(); 

    String multimediaPath=sc.getInitParameter("multimediaPath"); 
    int idSpace=((Space)RequestContextHolder.getRequestContext().getFlowScope().get("selectedSpace")).getIdSpace(); 

    FileImageOutputStream imageOutput=null; 
    File file=null; 

    try{ 
     switch (this.getIdRequest()) { 
      case "event": 
       file=new File(multimediaPath + File.separator + idSpace + File.separator + "events" + File.separator 
         + spaceBo.getDao().countSectionPages(idSpace,4)); 

       if(file.isDirectory()){ 
        int totalFiles=file.listFiles().length; 

       imageOutput=new FileImageOutputStream(new File(file.getAbsolutePath() 
         + "temp_pic_" + totalFiles + ".jpg")); 
       } 

       //MARCAR ERRORES si no es un DIRECTORIO 
       break; 

      case "configuration": 
       file=new File(multimediaPath + File.separator + idSpace + File.separator + "tempCrop.jpeg"); 
       imageOutput=new FileImageOutputStream(file); 

       break; 

      default: 
       break; 
     } 


     if(imageOutput!=null){ 
      imageOutput.write(croppedImage.getBytes(),0,croppedImage.getBytes().length); 
      imageOutput.close(); 
      this.setFlagCropper(false); 
      this.setFlagSave(true); 
     } 

     RequestContext requestContext=RequestContextHolder.getRequestContext(); 
     RequestControlContext rec = (RequestControlContext) requestContext; 

     //rec.handleEvent(new Event(this,"yes")); 
    }catch (Exception e){ 
     e.printStackTrace(); 
     //ARREGLAR 
    } 
} 
} 

回答

0

我已經找到解決方案的另一個計算器post,現在每一個瀏覽器顯示右圖,當我重新上傳用ajax這些的。這是@BalusC的回答:

告訴瀏覽器不緩存圖像。之前的第一位是曾經被寫過它身體上設置servlet響應以下標題:

response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1. 
response.setHeader("Pragma", "no-cache"); // HTTP 1.0. 
response.setDateHeader("Expires", 0); // Proxies. 

爲了防止強硬的瀏覽器還是從它的緩存,timestampto servlet的URL以添加一個請求參數。

<h:graphicImage value="imageServlet?id=#{bean.imageId}&amp;t=#{now.time}" /> 

#{now}被登記在faces-config.xml如下:

<managed-bean> 
    <managed-bean-name>now</managed-bean-name> 
    <managed-bean-class>java.util.Date</managed-bean-class> 
    <managed-bean-scope>request</managed-bean-scope> 
</managed-bean>