2012-12-03 14 views
5

Voglio fare una disposizione per scaricare tutti i tipi di file ... C'è un modo per scaricare qualsiasi formato di file in jsp ...Quale dovrebbe essere il tipo di contenuto per scaricare qualsiasi formato di file in jsp?

mio frammento di codice:

String filename = (String) request.getAttribute("fileName");   
    response.setContentType("APPLICATION/OCTET-STREAM"); 
    String disHeader = "Attachment"; 
    response.setHeader("Content-Disposition", disHeader); 

    // transfer the file byte-by-byte to the response object 
    File fileToDownload = new File(filename); 
    response.setContentLength((int) fileToDownload.length()); 
    FileInputStream fileInputStream = new FileInputStream(fileToDownload); 
    int i = 0; 
    while ((i = fileInputStream.read()) != -1) { 
     out.write(i); 
    } 
    fileInputStream.close(); 

Se specifico setContentType come APPLICAZIONE/OCTET-STREAM, pdf, testo, file doc vengono scaricati .... Ma il problema è con i file di immagine ...

Qual è il problema con i file di immagine? Vorrei scaricare tutti i tipi di file immagine ...

ho cercato simili domande ma non ho trovato risposta adeguata ... Grazie ...

+2

provare, response.setHeader (, "attaccamento "Content-Disposition"'; nomefile = "+ nomefile);' – adatapost

+2

C'è [un'infarinatura completa di tipi di immagini mime] (http://www.webmaster-toolkit.com/mime-types.shtml), e paga essere specifico. – Makoto

+0

@AVD: Ho provato che ... non aiuta :( – loknath

risposta

3

Finalmente sono riuscito in qualche modo a fare questo ... Il problema è con JSP di " out.write", che non è in grado di flusso di scrittura di byte ...

ho sostituito jsp file con servlet ...

Il frammento di codice è:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
    try { 
     String filename = (String) request.getAttribute("fileName"); 
     response.setContentType("application/octet-stream"); 
     response.setHeader("Content-Disposition", 
       "attachment;filename="+filename); 

     File file = new File(filename); 
     FileInputStream fileIn = new FileInputStream(file); 
     ServletOutputStream out = response.getOutputStream(); 

     byte[] outputByte = new byte[(int)file.length()]; 
     //copy binary contect to output stream 
     while(fileIn.read(outputByte, 0, (int)file.length()) != -1) 
     { 
     out.write(outputByte, 0, (int)file.length()); 
     } 
    } 

Ora posso scaricare qualsiasi tipo di file ....

Grazie per i responces :)

Problemi correlati