通过HTTP Get in java下载文件 [英] Download a file through an HTTP Get in java

查看:249
本文介绍了通过HTTP Get in java下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个下载Servlet来返回基于messageID参数的文件。下面是doGet方法。

I've written a download Servlet to return a file based on a messageID parameter. Below is the doGet method.

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

然后我写了一些代码来检索文件。

I then wrote some code to retrieve the file.

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

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

Now this code works fine. I can download the audio file and it works correctly. What I want to know is how to, if possible, get the name of the file as it is downloaded instead of giving it my own name. Also, is it possible to get the file without having to read from the stream (maybe some library that does it for you)? I kind of want to hide the dirty stuff.

谢谢

推荐答案

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

With attachment, the file will be served with the provided name properly. When inline, browsers seem to ignore filename, and usually give the servletname part of the URL as default name when saving the inline contents.

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

You could try mapping that URL to an appropriate filename, if that is suitable.

这是一个与SO相关的问题:使用正确的文件名在浏览器中安全下载文件

Here's a SO related question: Securly download file inside browser with correct filename

您可能还会发现此链接很有用:内联内容的文件名属性 - 处理无意义?

You may also find this link useful: Filename attribute for Inline Content-Disposition Meaningless?

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

I think you cannot download file without streaming. For I/O you must use stream.

这篇关于通过HTTP Get in java下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆