Java下載服務器文件到前端


直奔主題!

Java代碼

/**
* 下載文件
* @param path
* @param fileName
* @param response
*/
public static void downLoad(String path, String fileName,HttpServletResponse response) {
	// 服務器保存的文件地址,即你要下載的文件地址(全路徑)
	File file = new File(path);
	InputStream inputStream = null;
	OutputStream outputStream = null;
	try {
		inputStream = new BufferedInputStream(new FileInputStream(file));
		byte[] buffer = new byte[inputStream.available()];
		inputStream.read(buffer);
		response.reset();
		response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
		response.addHeader("Content-Length", "" + file.length());
		response.setContentType("application/octet-stream");
		outputStream = new BufferedOutputStream(response.getOutputStream());
		outputStream.write(buffer);
		outputStream.flush();
	}
	catch (IOException e) {
		e.printStackTrace();
		throw new GGException(e.getMessage());
	}
	finally {
		try {
			if (outputStream != null) {
				outputStream.close();
			}
			if (inputStream != null) {
				inputStream.close();
			}
		}
		catch (IOException e) {
			e.printStackTrace();
		}
	}
}

前端代碼

// 下載文件
function downLoad(sid, fileName) {
    var url = "/file/downFileBySid?sid=" + sid;
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = "blob";
    xhr.onload = function() {
        if (this.status === 200) {
            debugger
            var blob = this.response;
            var reader = new FileReader();
            reader.readAsDataURL(blob);
            reader.onload = function(e) {
                var a = document.createElement('a');
                a.download = fileName;
                a.href = e.target.result;
                $('body').append(a);
                a.click();
            }
        } else {
            alert("下載失敗");
        }
    };
    xhr.send();
}

最開始用jqueryajax發起請求,直接在response中返回的是文件流,沒有blob類型返回格式。
苦惱了好半天,希望大家別走彎路。
如果你用swagger測試請求會直接給你生成一個下載連接,它自己內部處理了,但我們只能依賴a鏈接形式。
附一個比較好的類似文章,供大家參考。Java下載文件


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM