1. 程式人生 > >檔案下載 瀏覽器直接開啟檔案而不是儲存 相關問題

檔案下載 瀏覽器直接開啟檔案而不是儲存 相關問題

昨天做SpringMVC 檔案上傳下載功能時遇到一堆問題。其中有個問題就是txt css js html xml pdf 等等檔案下載時瀏覽器(html5的a標籤download屬性不是所有瀏覽器都支援的)是直接開啟,而不是下載儲存。網上有許多解決的方法,我這邊只是整合下,做個mark。

場景就是有個url,老大提醒說用後臺訪問url獲取檔案流 前臺來處理。。大概這個流程 程式碼如下:

//得到拼接字串
function getFJInfo(name, url) {
	return "<tr><td style=''><a  href='javascript:void(0)' onclick='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)
}

/**
     * 返回流
     * 
     * @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;
    }

先這樣吧。。老大說還有更高大上的。過段時間再看看