通过HTTP Get in java下载文件

时间:2012-01-06 04:59:52

标签: java java-ee

我编写了一个下载Servlet,用于根据messageID参数返回文件。以下是doGet方法。

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

    // This messageID would be used to get the correct file eventually
    long messageID = Long.parseLong(request.getParameter("messageID"));
    String fileName = "C:\\Users\\Soto\\Desktop\\new_audio1.amr";
    File returnFile = new File(fileName);


    ServletOutputStream out = response.getOutputStream();
    ServletContext context = getServletConfig().getServletContext();
    String mimetype = context.getMimeType("C:\\Users\\Soto\\Desktop\\new_audio1.amr");

    response.setContentType((mimetype != null) ? mimetype : "application/octet-stream");
    response.setContentLength((int)returnFile.length());
    response.setHeader("Content-Disposition", "attachment; filename=\"" + "new_audio.amr" + "\"");

    FileInputStream in = new FileInputStream(returnFile);
    byte[] buffer = new byte[4096];

    int length;
    while((length = in.read(buffer)) > 0) {
        out.write(buffer, 0, length);
    }
    in.close();
    out.flush();
}
然后我写了一些代码来检索文件。

String url = "http://localhost:8080/AudioFileUpload/DownloadServlet";
    String charset = "UTF-8";

    // The id of the audio message requested
    String messageID = "1";

    //URLConnection connection = null;


    try {   
        String query = String.format("messageID=%s", URLEncoder.encode(messageID, charset));
        //URLConnection connection;
        //URL u = new URL(url + "?" + query);

        //connection = u.openConnection();
        //InputStream in = connection.getInputStream();

        HttpClient httpClient = new DefaultHttpClient();
        httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);


        HttpGet httpGet = new HttpGet(url + "?" + query);
        HttpResponse response = httpClient.execute(httpGet);

        System.out.println(response.getStatusLine());

        InputStream in = response.getEntity().getContent();

        FileOutputStream fos = new FileOutputStream(new File("C:\\Users\\Soto\\Desktop\\new_audio2.amr"));

        byte[] buffer = new byte[4096];
        int length; 
        while((length = in.read(buffer)) > 0) {
            fos.write(buffer, 0, length);
        }
        //connection = new URL(url + "?" + query).openConnection();
        //connection.setRequestProperty("Accept-Charset", charset);

        //InputStream response = connection.getInputStream();

    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

现在这段代码工作正常。我可以下载音频文件,它可以正常工作。我想知道的是,如果可能的话,如何在下载时获取文件的名称,而不是给它自己的名字。此外,是否可以获取文件而无需从流中读取(可能是某些库为您执行此操作)?我有点想隐藏脏东西。

谢谢

2 个答案:

答案 0 :(得分:1)

要设置下载文件名,请在Servlet代码

中的响应对象上执行以下操作
 response.setHeader("Content-disposition",
                  "attachment; filename=" +
                  "new_audio1.amr" );

编辑: 我看到你已经在做了。只需尝试删除已添加的斜杠。

答案 1 :(得分:0)

使用附件,文件将正确提供所提供的名称。在内联时,浏览器似乎忽略了文件名,并且在保存内联内容时通常会将URL的servletname部分作为默认名称。

如果合适,可以尝试将该URL映射到适当的文件名。

以下是与SO相关的问题:Securly download file inside browser with correct filename

您可能还会发现此链接很有用:Filename attribute for Inline Content-Disposition Meaningless?

我认为你不能在没有流媒体的情况下下载文件。对于I / O,您必须使用流。