简体   繁体   中英

Getting the browser to save a downloaded file

I am working with an app to learn JavaEE file handling

I am using Netbeans 8.0.1, Wildfly 8, JPA and Primefaces.

I have only one objet with 4 properties

@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);

    }

This method works fine, the record is added to the database

Then I also made a datatable, it works fine and it shows every record in the database,also to test that every file is being retrieved I use a outputtext that gives me the weight in bytes of every file, and it does it well

<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>

NOw my challenge is to make the user download directly the file from the object in the memory, I tried a lot of things but nothing seems to work, .

The last thing I did was a method getFile(File file) that you can see in the above CommandLInk that calls the following method

 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;

        } 

THat method brings me from the database the file storaged and copies it in the folder /home/alex/files, what I want to do is to make this method to download normaly the file allocated in the objects file property directly

ANy idea?

I actually solve the thing

@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();     
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM