前臺ajax請求後臺實現下載
下面是大致程式碼。
jsp頁面:
function getDada(){
var returnFilePath = "";
....
...
$.ajax({
url: "a/b",
data: {data1: data1,data2: data2,},
type: "post",
async: false, // 必須同步
success: function (data) {
returnFilePath = data;
}
});
return returnFilePath;
}
要在後臺實現下載頁面需要增加一個函式:
function getDada() {
var filePath = getDada();
window.location.href = "a/c?filePath="+encodeURI(encodeURI(filePath));
}
java後臺:
// 建立檔案
@RequestMapping("/getDada")
public void getDada(String data1,String data2,HttpServletRequest request,HttpServletResponse response) throws Exception{
.....
.....
try {
String fileTime = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date().getTime());
String filePath = request.getSession().getServletContext().getRealPath("/") + "WEB-INF\\note.sql";
System.out.println("filePath==="+filePath);
File f = new File(filePath);
if (f.exists()) {
System.out.print("檔案存在");
} else {
System.out.print("檔案不存在");
f.createNewFile();// 不存在則建立
}
str = sb.toString();
BufferedWriter output = new BufferedWriter(new FileWriter(f));
output.write(str);
output.close();
response.getWriter().write(filePath); // 將路徑返回到頁面,即ajax請求返回的結果
} catch (Exception e) {
e.printStackTrace();
}
}
// 下載
@RequestMapping("/downloadFile")
public static void download(String filePath, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
filePath = URLDecoder.decode(request.getParameter("filePath"), "UTF-8");
String fileName = filePath.substring(filePath.lastIndexOf("\\")+1);
response.reset();
response.setContentType("application/octet-stream");
//如果輸出的是中文名的檔案,在此處就要用URLEncoder.encode方法進行處理
response.setHeader("Content-Disposition", "attachment; filename="+URLEncoder.encode(fileName, "UTF-8"));
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
FileInputStream fis = null;
OutputStream fos = null;
File fPath = new File(filePath);
try {
if (fPath.exists()) {
fis = new FileInputStream(filePath);
bis = new BufferedInputStream(fis);
fos = response.getOutputStream();
bos = new BufferedOutputStream(fos);
int bytesRead = 0;
byte[] buffer = new byte[5 * 1024];
while ((bytesRead = bis.read(buffer)) != -1) {
bos.write(buffer, 0, bytesRead);// 將檔案傳送到客戶端
}
} else {
System.out.print("檔案不存在");
}
} catch (Exception e) {
e.printStackTrace();
} finally{
try {
if (bos != null) {
bos.close();
}
if(fos != null){
fos.close();
}
if(bis != null){
bis.close();
}
if(fis != null){
fis.close();
}
// 下載完成後刪除伺服器上的原檔案
fPath.delete();
} catch (IOException e) {
e.printStackTrace();
}
}
}