一、需求:平時(shí)寫圖片下載功能,只需要前臺(tái)頁(yè)面寫download標(biāo)簽就可以實(shí)現(xiàn)圖片的下載,本次項(xiàng)目遇到的問題是,由于搭建了圖片服務(wù)器,請(qǐng)求圖片URL的時(shí)候獲取不到請(qǐng)求頭,瀏覽器無(wú)法識(shí)別圖片是文件,導(dǎo)致點(diǎn)擊下載,瀏覽器會(huì)打開圖片.
二、解決:既然瀏覽器獲取不到請(qǐng)求頭,考慮到的最簡(jiǎn)單的解決方式是通過后臺(tái)下載,向圖片服務(wù)器發(fā)送請(qǐng)求頭.
考慮到下載圖片使用頻繁,所以把下載圖片封裝為通用方法,代碼如下:
實(shí)現(xiàn)步驟:
1.前臺(tái)向后臺(tái)發(fā)送圖片url
2.通過url獲取圖片流
3.設(shè)置輸出頭
4.把圖片輸出到瀏覽器(不是寫死圖片地址)
/**
* 圖片下載
* @param fileUrl
* @param response
*/
@ApiOperation(value = "|uploadQianURL|圖片下載")
@GetMapping("/uploadQianURL")
public void uploadQianURL(String fileUrl,HttpServletResponse response) {
fileUrl = fileUrl.replace("\\", "/");
//獲取文件名,文件名實(shí)際上在URL中可以找到
String[] strs=fileUrl.split("/");
String fileName = strs[strs.length - 1].toString();
try {
URL url = new URL(fileUrl);/*將網(wǎng)絡(luò)資源地址傳給,即賦值給url*/
/*此為聯(lián)系獲得網(wǎng)絡(luò)資源的固定格式用法,以便后面的in變量獲得url截取網(wǎng)絡(luò)資源的輸入流*/
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
DataInputStream in = new DataInputStream(connection.getInputStream());
ServletOutputStream out=response.getOutputStream();
response.setContentType("multipart/form-data");
//獲取當(dāng)前超鏈接中文件的名字
response.addHeader("Content-Disposition","attachment; filename="+ new String(fileName.getBytes("GB2312"), "ISO8859-1"));
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
byte[] context=output.toByteArray();
out.write(output.toByteArray());
in.close();
out.close();
connection.disconnect();
} catch (Exception e) {
}
}