前端非同步請求獲取圖片下載
前端主要部分
<script type="text/javascript">
$(document).ready(function(){
$("#cardImg").on('click', function(){
const xhr = new XMLHttpRequest();
var url = 'getImg.action';
var param ='path='+ $(this).attr("url");
xhr.open('POST', url, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");
xhr.responseType = 'blob';
xhr.onload = function(){
if (xhr.status === 200) {
//將圖片檔案用瀏覽器中下載
saveAs(xhr.response, "cardImg.jpg");
}
};
xhr.send(param);
});
$("#cardImgBack").on('click', function(){
const xhr = new XMLHttpRequest();
var url = 'getImg.action';
var param ='path='+ $(this).attr("url");
xhr.open('POST', url, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");
xhr.responseType = 'blob';
xhr.onload = function(){
if (xhr.status === 200) {
//將圖片檔案用瀏覽器中下載
saveAs(xhr.response, "cardImgBack.jpg");
}
};
xhr.send(param);
});
});
</script>
<body>
<a id = 'cardImg' href= 'javascript:void(0);'
url='圖片相對路徑'
>下載</a>
<a id = 'cardImgBack' href= 'javascript:void(0);'
url='圖片相對路徑'
>下載</a>
</body>
服務端
getImg.action實現 主要部分
public String execute() throws Exception {
ServletOutputStream out = null;
String fileServer = “可以訪問圖片的域名或路徑”;
String imgPath = request_.getParameter("path");
try {
//獲取圖片存放路徑
String imgUrl = fileServer + imgPath;
log.info("圖片真實路徑: "+ imgUrl);
URL url = new URL(imgUrl);
SslUtils.ignoreSsl();
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5 * 1000);
InputStream input = conn.getInputStream();//通過輸入流獲取圖片資料
response_.setContentType("multipart/form-data");
out = response_.getOutputStream();
//讀取檔案流
int len = 0;
byte[] buffer = new byte[1024 * 10];
while ((len = input.read(buffer)) != -1){
out.write(buffer,0,len);
}
out.flush();
}catch (Exception e){
e.printStackTrace();
}finally {
if (out != null) {
out.close();
}
}
return null;
}
struts.xml 配置
<action name="getImg" class="action位置">
</action>