簡體   English   中英

讓瀏覽器保存下載的文件

[英]Getting the browser to save a downloaded file

我正在使用一個應用程序來學習 JavaEE 文件處理

我正在使用 Netbeans 8.0.1、Wildfly 8、JPA 和 Primefaces。

我只有一個有 4 個屬性的對象

@Id @GeneratedValue (strategy = GenerationType.IDENTITY) private int id_articulo;

private String titulo;

private String descripcion;


@Lob
private File archivo;

I made a form to upload data including the file as a blob, the form call a method in a backing bean




public void generarArticulo() throws IOException{


        File destFile= new File(fichero.getFileName());
    FileUtils.copyInputStreamToFile(fichero.getInputstream(), destFile);

        articulo a = new articulo();
        a.setArchivo(destFile);
        a.setTitulo(titulo);
        a.setDescripcion(descripcion);


        this.controlador.registrarArticulo(a);

    }

這個方法工作正常,記錄被添加到數據庫中

然后我還制作了一個數據表,它工作正常,它顯示了數據庫中的每條記錄,還測試每個文件是否正在被檢索我使用了一個輸出文本,它為我提供了每個文件的字節權重,並且它做得很好

<p:dataTable var="articulos" value="#{listadoArticulos.listado}" 
                         rows="10"
                         paginator="true"
                         >
                    <p:column headerText="Titulo" sortBy="#{articulos.titulo}" >
        <h:outputText value="#{articulos.titulo}"  />
    </p:column>
    <p:column headerText="Descripcion" >
        <h:outputText value="#{articulos.descripcion}" />
    </p:column>
  [B]<p:column headerText="Fichero" >
      <h:outputText value="#{articulos.archivo.name} y pesa #{articulos.archivo.length()}"  />
    </p:column>[/B]

          <p:column headerText="Descarga">
              <p:commandLink action="#{articuloBean.getFichero(articulos.archivo)}" value="Descargar"/>

    </p:column>          

</p:dataTable>

現在我的挑戰是讓用戶直接從內存中的對象下載文件,我嘗試了很多東西但似乎沒有任何效果,.

我做的最后一件事是一個方法 getFile(File file) ,你可以在上面的 CommandLInk 中看到它調用以下方法

 public FileOutputStream getFichero (File file) throws FileNotFoundException, IOException {

       FileInputStream in = new FileInputStream (file);
       FileOutputStream out = new FileOutputStream("/home/alex/ficheros/"+file.getName());
       int c;

       while ((c = in.read()) != -1) {
                out.write(c);
            }

       return out;

        } 

該方法從數據庫中獲取存儲的文件並將其復制到文件夾 /home/alex/files 中,我想要做的是使該方法能夠正常下載對象文件屬性中分配的文件

任何的想法?

我實際上解決了問題

@WebServlet("/DownloadFileServlet")
public class DownloadFileServlet extends HttpServlet {

    @Inject
    ArticuloControlador controlador;


    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {


        String x=request.getParameter("x");
        int id = Integer.parseInt(x);

        articulo a = controlador.getArticuloporID(id);
        File f = a.getArchivo();

        FileInputStream inStream = new FileInputStream(f);

        String relativePath = getServletContext().getRealPath("");
        System.out.println("relativePath = " + relativePath);

        // obtengo ServletContext
        ServletContext context = getServletContext();

        // obtengo MIME del fichero
       String mimeType= URLConnection.guessContentTypeFromName(f.getName());

        if (mimeType == null) {        
            // steamos el MIME type si no lo encontramos
            mimeType = "application/octet-stream";
        }
        System.out.println("MIME type: " + mimeType);

        // modificamos el response
        response.setContentType(mimeType);
        response.setContentLength((int) f.length());

        // Descargamos
        String headerKey = "Content-Disposition";
        String headerValue = String.format("attachment; filename=\"%s\"", f.getName());
        response.setHeader(headerKey, headerValue);


        OutputStream outStream = response.getOutputStream();

        byte[] buffer = new byte[4096];
        int bytesRead = -1;

        while ((bytesRead = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, bytesRead);
        }

        inStream.close();
        outStream.close();     
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM