效果展示:
后台代码:
工具类:
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
/**
* @Desc
* @Author madengling
* @Time 2020/10/26 14:50
*/
public class FileDownloadUtil {
private static final Logger log = LoggerFactory.getLogger(FileDownloadUtil.class);
/**
* 利用浏览器自带下载
* 附件下载 工具方法
* 通过附件地址获取到文件流返回给前端
*/
public static void DownloadFj(HttpServletResponse response, String fileName, String fileUrl) {
OutputStream out = null;
InputStream is = null;
try {
response.setContentType("application/octet-stream");
if(fileName==null || StringUtils.isEmpty(fileName)){
String fileType = "";
if(fileUrl.contains("?")){
fileType = fileUrl.substring(fileUrl.lastIndexOf(".") + 1,fileUrl.indexOf("?"));
}else {
fileType = fileUrl.substring(fileUrl.lastIndexOf(".") + 1);
}
fileName = UUID.randomUUID().toString()+"."+fileType;
}
//设置附件下载的名字,如果没有设定名字,默认用UUID创建一个
response.setHeader("Content-disposition", "attachment; filename=" + fileName);
out = response.getOutputStream();
CloseableHttpClient httpClient = HttpClients.createDefault();
RequestConfig requestConfig = RequestConfig.DEFAULT;
HttpGet request = new HttpGet(fileUrl);
request.setConfig(requestConfig);
try {
CloseableHttpResponse httpResponse = httpClient.execute(request);
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED) {
request.abort();
} else {
HttpEntity entity = httpResponse.getEntity();
if (null != entity) {
is = entity.getContent();
}
}
} catch (Exception e) {
e.printStackTrace();
request.abort();
}
if (is != null) {
int zlen = 0;
int len = 0;
byte[] buffer = new byte[1024 * 100];
while ((len = is.read(buffer)) > 0) {
zlen = zlen + len;
out.write(buffer, 0, len);
}
out.flush();
}
}catch (IOException e){
e.printStackTrace();
}finally {
try {
if (is != null){
is.close();
}
response.flushBuffer();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
控制层:
import com.mdl.mall.util.FileDownloadUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.http.HttpServletResponse;
import java.net.MalformedURLException;
import java.util.UUID;
/**
* @Desc
* @Author madengling
* @Time 2020/10/16 9:18
*/
@Controller
@RequestMapping("user")
public class UserController {
@RequestMapping("/download")
public void downloadFile(HttpServletResponse response) {
String fileUrl = "http://reept.zjfw.gov.cn/oss//form/418-372b11d634.jpg";
// String fileName = UUID.randomUUID().toString()+".jpg";
FileDownloadUtil.DownloadFj(response,null,fileUrl);
}
}
页面:
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>测试页面</title>
<link rel="stylesheet" type="text/css" href="../css/easyui/default/easyui.css">
<link rel="stylesheet" type="text/css" href="../css/easyui/icon.css">
<script src="../js/jquery/jquery.min.js"></script>
<script src="../js/easyui/jquery.easyui.min.js"></script>
</head>
<body>
<!--html5需要用a标签的download属性,href指定到后台方法获取文件流,如果直接放地址会直接显示出文件,而非下载-->
<a href="/user/download" class="easyui-linkbutton" icon="icon-save" download>下载</a>
<div>
<img src="http://recept.zwfw.gov.cn/oss//form/4ec-921b11d634.jpg" alt="测试" width="500px" height="800px"/>
</div>
<script></script>
</body>
</html>
为了直接下载,模拟代码中没有传下载路径,直接在调用方法中写死了路径(图片路径是错误的,请自行修改成正确地址,如果自己想用的话在前后端交互的时候将路径传入即可。
自动下载其实只是前端利用了浏览器默认下载,跟后台没有什么关系