2012-06-01 2 views
1

Я пытаюсь добавить конкретный компонент диалога для действия в Alfresco Explorer, который должен загрузить определенный файл docx. Код работает нормально, когда я нажимаю действие загрузки, он загружает файл, но, как упоминалось в моем заголовке вопроса, размер файла равен 0 байтам.Загруженный размер файла 0

Я использую это, чтобы сделать это:

public class NewFormDialog extends BaseDialogBean { 

protected String aspect; 

protected String finishImpl(FacesContext context, String outcome) 
     throws Exception { 

    download(aspect); 

    // // get the space the action will apply to 
    // NodeRef nodeRef = this.browseBean.getActionSpace().getNodeRef(); 
    // 
    // // resolve the fully qualified aspect name 
    // QName aspectToAdd = Repository.resolveToQName(this.aspect); 
    // 
    // // add the aspect to the space 
    // getNodeService().addAspect(nodeRef, aspectToAdd, null); 
    // 
    // // return the default outcome 
    return outcome; 
} 

public boolean getFinishButtonDisabled() { 
    return false; 
} 

public String getFinishButtonLabel() { 
    return "Download"; 
} 

public void download(String pAspect) throws ServletException, IOException { 

    String filename = pAspect; 
    String filepath = "\\"; 
    BufferedInputStream buf = null; 
    ServletOutputStream myOut = null; 

    try { 
     FacesContext fc = FacesContext.getCurrentInstance(); 
     HttpServletResponse response = (HttpServletResponse) fc 
       .getExternalContext().getResponse(); 

     myOut = response.getOutputStream(); 
     File myfile = new File(filepath + filename); 

     // set response headers 
     response.setContentType("application/octet-stream"); 

     response.addHeader("Content-Disposition", "attachment; filename=" 
       + filename); 

     response.setContentLength((int) myfile.length()); 

     FileInputStream input = new FileInputStream(myfile); 
     buf = new BufferedInputStream(input); 
     int readBytes = 0; 

     // read from the file; write to the ServletOutputStream 
     while ((readBytes = buf.read()) != -1) 
      myOut.write(readBytes); 
     myOut.flush(); 
     response.flushBuffer(); 

    } catch (IOException ioe) { 

     throw new ServletException(ioe.getMessage()); 

    } finally { 
     // close the input/output streams 
     if (myOut != null) 
      myOut.close(); 
     if (buf != null) 
      buf.close(); 
     FacesContext.getCurrentInstance().responseComplete(); 
    } 
} 

public String getAspect() { 
    return aspect; 
} 

public void setAspect(String aspect) { 
    this.aspect = aspect; 
} 
} 

Я попытался каждое решение, которое я нашел на никто не работает.

Заранее спасибо.

ответ

2

Метод File.length() возвращает 0, если файл не существует. Убедитесь, что файл существует.

Совет:Apache Commons IO library упрощает многие связанные с I/O задачи. Например, следующий фрагмент кода передает содержимое файла в ответ сервлета:

HttpServletResponse response = ... 
File myfile = ... 
InputStream in = null; 
OutputStream out = null; 
try { 
    in = new FileInputStream(myfile); 
    out = response.getOutputStream(); 
    IOUtils.copy(in, out); 
} finally { 
    IOUtils.closeQuietly(in); //checks for null 
    IOUtils.closeQuietly(out); //checks for null 
} 
+0

На самом деле, я думаю, что я ошибаюсь в этом пути. Я использую что-то вроде этого для пути к файлу «http: // localhost: 8080/alfresco/d/a/workspace/SpacesStore/space1 /», но я перезапускаю сервер, чтобы попробовать: «localhost: 8080 \ \ \\ d под открытым небом \\ а \\ рабочее пространство \\ SpacesStore \\ пространство1 \\» Я только что проверил файл журнала Tomcat и я нашел этот ' Вызванный: javax.servlet.ServletException: файл не найден \t в \t ... 54 больше' Благодарим за внимание. – Emowpy

+0

Emowpy Вы можете отметить мой вопрос как ответ? – Michael

+0

Проблема решена. Это была проблема пути, мне пришлось сделать что-то вроде «C: \ Alfresco \\». Теперь он работает отлично. Еще раз спасибо за ваш совет @ Майкл. – Emowpy

Смежные вопросы