java 如何使用 Spring MVC 从 url 下载文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10991089/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 03:19:19  来源:igfitidea点击:

How to download file from url using Spring MVC?

javajspspring-mvcdownload

提问by Rahul

I am having download option in my jsp like this

我的jsp中有这样的下载选项

<a href='<c:url value="/licensing/download.sp?name=${namelist.name}&downloadUrl=${namelist.url}"/>'>

<img src="/images/download.gif" alt="Download" border="0" align="right">

In the above "url" is the location of file and name is the file name.On click of download option in jsp iam calling the controller method download,in controller

在上面的“url”是文件的位置,name是文件名。点击jsp中的下载选项,调用控制器方法下载,在控制器中

public ModelAndView download(HttpServletRequest request, HttpServletResponse response, DevTechBean devTechBean) throws Exception {
        cat.debug("MySuiteListController: download: begin");
        ModelAndView modelView = super.handleLicensingRequest(request, response);
        String name = request.getParameter("name");

        String url1 = request.getParameter("downloadUrl");
        cat.debug(" download: url ="+url1);

        String downloadurl1="https://my.net:8869"+url1;
        cat.debug(" download: downloadurl ="+downloadurl1);
    try{
        URL url = new URL(downloadurl1);  
        //response.setHeader("Content-Type", "text/csv");  
        response.setHeader("Content-disposition", "attachment;filename="+name);
        URLConnection connection = url.openConnection();
        InputStream stream = connection.getInputStream();
        BufferedOutputStream outs = new BufferedOutputStream(response.getOutputStream());
        int len;
        byte[] buf = new byte[1024];
        while ((len = stream.read(buf)) > 0) {
          outs.write(buf, 0, len);
        }
        outs.close();
    }
    catch (MalformedURLException e) { 
        cat.error("Error occurrred in url");

    } 
    catch (IOException e) { 
        cat.error("Error occurrred ");

    }
        String viewName = "swl_download";
    modelView.setViewName(viewName);
return modelView;       

}

But when i click on download i am getting file not found exception. Iam thinking that problem is due to the url value. In the above iam having value of downloadurl=/files/download/hai.txt

但是当我点击下载时,我发现文件未找到异常。我认为这个问题是由于 url 值造成的。在上面的 iam 中具有 downloadurl=/files/download/hai.txt 的值

when i give

当我给

<a href="${namelist.url}"/>
<img src="/images/download.gif" alt="Download" border="0" align="right"></a><br/><br/></td>

on click the file is opening in browser with the url https://my.net:8869//files/download/hai.txt(buthere for href iam giving only this link "/files/download/hai.txt" dont know how the entire link is coming.

单击该文件将在浏览器中打开,网址为https://my.net:8869//files/download/hai.txt(但这里的 href iam 仅提供此链接“/files/download/hai.txt”知道整个链接是如何来的。

but if give link like this to call the controller for opening that file as pop up.

但是如果给出这样的链接来调用控制器来打开那个文件作为弹出。

<a href='<c:url value="/download.sp?name=${namelist.name}&downloadUrl=${namelist.url}"/>'>

it is getting file not found exception. I think it is due that do downloadUrl.so i have added like this in above

它正在获取文件未找到异常。我认为这是因为 downloadUrl.so 我在上面添加了这样的内容

String downloadurl1="https://my.net:8869"+url1;

But i am getting file not find exception.Please help me resolving this.

但我收到文件未找到异常。请帮我解决这个问题。

回答by Andrea Girardi

Try this:

试试这个:

@RequestMapping(value="/viewAttach", method = RequestMethod.GET)
public ModelAndView viewAttach(@RequestParam(value="article_id", required = true) String article_ref, HttpSession session, HttpServletResponse response) 
{

    /* *** Check Session *** */
    try {

        // Direclty from pier.content.GetContent written by ang94402

        URL url = new URL(binaryURL);           
        response.setHeader("Content-disposition", "attachment;filename=" + binary.getName());

        //Set the mime type for the response
        response.setContentType("application/pdf");

        // URLConnection connection = url.openConnection();
        InputStream is = url.openStream();

        BufferedOutputStream outs = new BufferedOutputStream(response.getOutputStream());
        int len;
        byte[] buf = new byte[1024];
        while ( (len = is.read(buf)) > 0 ) {
            outs.write(buf, 0, len);
        }
        outs.close();

    } catch (MalformedURLException e) {
        logger.error("Error ModelAndView.viewMain - MalformedURLException : " + e.toString() + " -- " + e.getStackTrace()[0].toString());
        return null;
    } catch (IOException e) {
        logger.error("Error ModelAndView.viewMain - IOException : " + e.toString() + " -- " + e.getStackTrace()[0].toString());
        return null;
    }


    return null;

}

回答by Ved

This is just a pseudo code. Change it as per your needs.

这只是一个伪代码。根据您的需要更改它。

 InputStream is = getClass().getResourceAsStream("filename");

First try to figure out that getClass() points to which directory.(Not sure, but it should be HOME of your App ?). Then place your file into same location, if its not.

首先尝试找出 getClass() 指向哪个目录。(不确定,但它应该是您的应用程序的 HOME ?)。然后将您的文件放在相同的位置,如果不是。

Hope this would help. source

希望这会有所帮助。 来源