简体   繁体   English

让浏览器保存下载的文件

[英]Getting the browser to save a downloaded file

I am working with an app to learn JavaEE file handling我正在使用一个应用程序来学习 JavaEE 文件处理

I am using Netbeans 8.0.1, Wildfly 8, JPA and Primefaces.我正在使用 Netbeans 8.0.1、Wildfly 8、JPA 和 Primefaces。

I have only one objet with 4 properties我只有一个有 4 个属性的对象

@Id @GeneratedValue (strategy = GenerationType.IDENTITY) private int id_articulo; @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我做的最后一件事是一个方法 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;

        } 

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该方法从数据库中获取存储的文件并将其复制到文件夹 /home/alex/files 中,我想要做的是使该方法能够正常下载对象文件属性中分配的文件

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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