最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

文件下载 浏览器直接打开文件而不是保存 相关问题

运维笔记admin3浏览0评论

昨天做SpringMVC 文件上传下载功能时遇到一堆问题。其中有个问题就是txt css js html xml pdf 等等文件下载时浏览器(html5的a标签download属性不是所有浏览器都支持的)是直接打开,而不是下载保存。网上有许多解决的方法,我这边只是整合下,做个mark。

场景就是有个url,老大提醒说用后台访问url获取文件流 前台来处理。。大概这个流程 代码如下:

前端js部分,参考http://www.alloyteam/2014/01/use-js-file-download/

//得到拼接字符串
function getFJInfo(name, url) {
	return "<tr><td style=''><a  href='javascript:void(0)' οnclick='getDownFile(\"" + url + "\",\"" + name + "\")'>" + name + "</a></td></tr>"
}
//文件下载
function getDownFile(url, name) {
	var param = {
		"url": url
	};
	$.ajax({
		url: contextPath + '/product-label/file2Stream',
		type: 'GET',
		data: Base64.encode(JSON.encode(param)),
		dataType: "text",
		success: function(data) {
			downloadFile(name, data)
		}
	})
}
//流处理触发下载事件
function downloadFile(fileName, content) {
	var aLink = document.createElement('a');
	var blob = new Blob([content]);
	var evt = document.createEvent("MouseEvents");
	evt.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
	aLink.download = fileName;
	aLink.href = URL.createObjectURL(blob);
	aLink.dispatchEvent(evt)
}

后台controller处理,参考http://blog.sina/s/blog_87216a0001014sm7.html

/**
     * 返回流
     * 
     * @param requestMap 请求参数
     * @param response 返回对象
     */
    @RequestMapping(value = "/file2Stream", method = RequestMethod.GET)
    public void file2Stream(@Json Map<String, Object> requestMap, HttpServletResponse response) {
        try {
            String url = String.valueOf(requestMap.get("url"));
            // URL url =new URL(String.valueOf(requestMap.get("url")));
            InputStream iStream = getFileStream(url);
            OutputStream stream = response.getOutputStream();
            stream.write(StreamUtils.getBytes(iStream));
            stream.flush();
            stream.close();
        } catch (Exception e) {
            LOG.error("ProductSalesRecommendController.file2Stream  error | ({})", e);
        }
    }

    /**
     * HttpURLConnection获取网络路径的文件流
     * 
     * @param url 链接
     * @return InputStream
     * @throws IOException
     */
    private InputStream getFileStream(URL url) throws IOException {
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5 * 1000);
        conn.setRequestMethod("GET");
        InputStream inStream = conn.getInputStream();
        return inStream;
    }

    /**
     * HttpClient获取网络路径的文件流
     * 
     * @param url 链接字符串
     * @return InputStream
     * @throws IllegalStateException
     * @throws IOException
     */
    private InputStream getFileStream(String url) throws IllegalStateException, IOException {
        HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, 5000); // 设置连接超时为5秒
        HttpClient client = new DefaultHttpClient(httpParams); // 生成一个http客户端发送请求对象
        HttpResponse httpResponse = client.execute(new HttpGet(url)); // 发送请求并等待响应
        HttpEntity entity = httpResponse.getEntity(); // 获取响应里面的内容
        InputStream inStream = entity.getContent();
        return inStream;
    }

先这样吧。。老大说还有更高大上的。过段时间再看看

发布评论

评论列表(0)

  1. 暂无评论
ok 不同模板 switch ($forum['model']) { /*case '0': include _include(APP_PATH . 'view/htm/read.htm'); break;*/ default: include _include(theme_load('read', $fid)); break; } } break; case '10': // 主题外链 / thread external link http_location(htmlspecialchars_decode(trim($thread['description']))); break; case '11': // 单页 / single page $attachlist = array(); $imagelist = array(); $thread['filelist'] = array(); $threadlist = NULL; $thread['files'] > 0 and list($attachlist, $imagelist, $thread['filelist']) = well_attach_find_by_tid($tid); $data = data_read_cache($tid); empty($data) and message(-1, lang('data_malformation')); $tidlist = $forum['threads'] ? page_find_by_fid($fid, $page, $pagesize) : NULL; if ($tidlist) { $tidarr = arrlist_values($tidlist, 'tid'); $threadlist = well_thread_find($tidarr, $pagesize); // 按之前tidlist排序 $threadlist = array2_sort_key($threadlist, $tidlist, 'tid'); } $allowpost = forum_access_user($fid, $gid, 'allowpost'); $allowupdate = forum_access_mod($fid, $gid, 'allowupdate'); $allowdelete = forum_access_mod($fid, $gid, 'allowdelete'); $access = array('allowpost' => $allowpost, 'allowupdate' => $allowupdate, 'allowdelete' => $allowdelete); $header['title'] = $thread['subject']; $header['mobile_link'] = $thread['url']; $header['keywords'] = $thread['keyword'] ? $thread['keyword'] : $thread['subject']; $header['description'] = $thread['description'] ? $thread['description'] : $thread['brief']; $_SESSION['fid'] = $fid; if ($ajax) { empty($conf['api_on']) and message(0, lang('closed')); $apilist['header'] = $header; $apilist['extra'] = $extra; $apilist['access'] = $access; $apilist['thread'] = well_thread_safe_info($thread); $apilist['thread_data'] = $data; $apilist['forum'] = $forum; $apilist['imagelist'] = $imagelist; $apilist['filelist'] = $thread['filelist']; $apilist['threadlist'] = $threadlist; message(0, $apilist); } else { include _include(theme_load('single_page', $fid)); } break; default: message(-1, lang('data_malformation')); break; } ?>