spring mvc + ajax實現無重新整理下載檔案
阿新 • • 發佈:2019-01-02
JQuery的ajax函式的返回型別只有xml、text、json、html等型別,沒有“流”型別,所以我們要實現ajax下載,不能夠使用相應的ajax函式進行檔案下載。但可以用js生成一個form,用這個form提交引數,並返回“流”型別的資料。在實現過程中,頁面也沒有進行重新整理。
前端程式碼:
<a href="JavaScript:downloadFile('${fileName }')">${fileName }</a><br>
function downloadFile(fileName){
var rootPath = this .getRootPath();//getRootPaht()自定義的方法,自行拼裝
if(fileName){
var form=$("<form>");//定義一個form表單
form.attr("style","display:none");
form.attr("target","");
form.attr("method","post");
form.attr("action",rootPath+'/downLoadFile');
var fileInput=$("<input>" );
fileInput.attr("type","hidden");
fileInput.attr("id","fileName");//設定屬性的名字
fileInput.attr("name","fileName");//設定屬性的名字
fileInput.attr("value",fileName);//設定屬性的值
$("body").append(form);//將表單放置在web中
form.append(fileInput);
form.submit();//表單提交
//form.remove();
}
}
後臺controller程式碼:
@RequestMapping("/downLoadFile")
@ResponseBody
public void downLoadFile(String fileName, HttpServletRequest request, HttpServletResponse response){
if(logger.isDebugEnabled()){
logger.debug("待下載檔案的名稱:"+fileName);
}
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try{
if(logger.isDebugEnabled()){
logger.debug("建立輸入流讀取檔案...");
}
//獲取輸入流
bis = new BufferedInputStream(new FileInputStream(new File(GlobalConfig.getConfig(UPLOAD_FILE_PAHT), fileName)));
//獲取輸出流
if(logger.isDebugEnabled()){
logger.debug("建立輸出流下載檔案...");
}
response.setCharacterEncoding("UTF-8");
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition", "attachment; filename="+ new String(fileName.getBytes("utf-8"), "ISO8859-1"));
bos = new BufferedOutputStream(response.getOutputStream());
//定義緩衝池大小,開始讀寫
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
//重新整理緩衝,寫出
bos.flush();
if(logger.isDebugEnabled()){
logger.debug("檔案下載成功。");
}
}catch(Exception e){
logger.error("檔案下載失敗"+e.getMessage());
}finally{
//關閉流
if(bis != null){
try {
bis.close();
} catch (IOException e) {
logger.error("關閉輸入流失敗,"+e.getMessage());
e.printStackTrace();
}
}
if(bis != null){
try {
bos.close();
} catch (IOException e) {
logger.error("關閉輸出流失敗,"+e.getMessage());
e.printStackTrace();
}
}
}
}
補充:如果頁面需要從後臺載入圖片,上面的controller可以直接使用,對應的jsp只需要新增img標籤即可
<img id="identityPaper2_js_showBox" title="顯示圖片" src="/downLoadFile/filename" style="width: 414px; height: 200px;">
img標籤src屬性可以直接接收圖片base64資料,也可以讓後臺直接返回base64資料,前臺將資料賦值給src屬性即可:
對應後臺程式碼調整:
@RequestMapping("/downLoadFile/{fileName}/{fileSuffix}")
@ResponseBody
public String downLoadFile(@PathVariable String fileName,@PathVariable String fileSuffix, HttpServletRequest request, HttpServletResponse response){
if(logger.isDebugEnabled()){
logger.debug("待下載檔案的名稱:"+fileName+",字尾:"+fileSuffix);
}
byte[] byData = new byte[]{};
try {
byData = FileUtils.readFileToByteArray(new File(GlobalConfig.getConfig(UPLOAD_FILE_PAHT),fileName+"."+fileSuffix));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String imgBase64Data = "data:image/jpg;base64,"+Base64Utils.encodeToString(byData);
return imgBase64Data;
}
前臺jsp,src屬性為空:
<img id="identityPaper2_js_showBox" title="顯示圖片" src="" style="width: 414px; height: 200px;">
處理的js:
$.get("${ctx}/agent/downLoadFile/2017041318120144084/jpg",function(data){
$("#identityPaper2_js_showBox").attr("src",data);
});