springmvc中网络文件下载

第一步。网络文件下载与从本地获取是不一样的,需要用URL类去打开连接从而获得输入流,其中path为完整路径包括http请求头的,inputStream注意在程序的finally中关闭,如下代码

 
 
/**
 * 获取外部文件流
 */
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(3 * 1000);
//防止屏蔽程序抓取而返回403错误
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
inputStream=conn.getInputStream();

第二步。需要将获得的输入流输出,输出的话需要借助response的outPutStream进行输出,注意文件名如果带有中文的话需要通过URLEncode.encode(filename,"UTF-8")进行转码

/**
 * 输出文件到浏览器
 */
int len=0;
// 输出下载的响应头,如果下载的文件是中文名,文件名需要经过url编码
response.setContentType("text/html;charset=utf-8");
response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(filename, "UTF-8"));
response.setHeader("Cache-Control", "no-cache");
out = response.getOutputStream();
while ((len = inputStream.read(buffer)) > 0) {
    out.write(buffer, 0, len);
}
out.flush();


第三步。关闭输入输出流

finally {
    if (inputStream != null) {
        try {
            inputStream.close();
        } catch (Exception e) {
            LogUtil.warn(logger, "关闭读取文件流出错", e);
        }
    }
    if (out != null) {
        try {
            out.close();
        } catch (Exception e) {
            LogUtil.warn(logger, "关闭下载文件流出错", e);
        }
    }
}

可能很多时候path完整路径需要自己拼接,这个时候可以通过springmvc中的request获得请求头,其中注意io操作都要捕获异常的,所以还需要try catch

String requestScheme= request.getScheme();  //请求协议http或则https



猜你喜欢

转载自blog.csdn.net/weixin_38907570/article/details/79502658