让浏览器保存下载的文件

时间:2015-09-28 23:44:42

标签: java http browser download

我正在使用应用程序来学习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(文件文件),您可以在上面的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中,我想做的就是让这个方法直接下载在objects文件属性中分配的文件

任何想法?

1 个答案:

答案 0 :(得分:0)

我实际上解决了这个问题

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