package cc.cloud.resourcecenter.web.controller;
import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import cc.cloud.resourcecenter.config.ThreadLocalCurrentUser;
import cc.cloud.resourcecenter.core.constant.ErrorCode;
import cc.cloud.resourcecenter.core.entity.ResourceCenterMapping;
import cc.cloud.resourcecenter.core.model.auth.CurrentUser;
import cc.cloud.resourcecenter.core.response.JsonResponse;
import cc.cloud.resourcecenter.util.JsonParserUtil;
import cc.cloud.resourcecenter.web.service.DownloadService;
import lombok.extern.log4j.Log4j;
/**
* @ClassName: DownloadController
* @Description: (文件下载)
* @date 2019年6月12日 下午3:07:05
* @version V1.0
*
*/
@Controller
@RequestMapping("download")
@Log4j
public class DownloadController {
@Autowired
private DownloadService downloadService;
/**
* @Title: getResourceCenterList
* @Description: (描述)
* @param @param response
* @param @param centerId
* @param @return 设定文件
* @return ResponseEntity<Object> 返回类型
* @throws
*/
@RequestMapping("file")
public void getResourceCenterList(HttpServletResponse request, HttpServletResponse response, Integer centerId, Integer accessoryId){
// String toekn = request.getHeader("token");
CurrentUser currentUser = ThreadLocalCurrentUser.getCurrentUser();
Integer schoolId = currentUser.getSchoolId();
List<ResourceCenterMapping> rcmList = null;
try {
// 获取该资源下所有的附件信息
rcmList = downloadService.getDownloadResourceCenterMappingByCenterId(schoolId, centerId, accessoryId);
if (null!=rcmList&&rcmList.size()>0) {
for (ResourceCenterMapping rm : rcmList) {
downloadService.downloadFile(response, schoolId, centerId, rm);
}
}else {
response.setStatus(200);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write(JsonParserUtil.DEFAULT.toJson(JsonResponse.fail(ErrorCode.ERROR_CODE_50016).getBody()));
}
} catch (Exception e) {
e.printStackTrace();
log.error("文件下载异常!");
try {
response.setStatus(200);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write(JsonParserUtil.DEFAULT.toJson(JsonResponse.fail(ErrorCode.ERROR_CODE_50013).getBody()));
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
package cc.cloud.resourcecenter.web.service;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import cc.cloud.resourcecenter.core.entity.ResourceCenterAccessory;
import cc.cloud.resourcecenter.core.entity.ResourceCenterMapping;
import cc.cloud.resourcecenter.core.mapper.MyResourceMapper;
import cc.cloud.resourcecenter.core.mapper.ResourceCenterMapper;
/**
* @ClassName: DownloadService
* @Description: (描述)
* @date 2019年6月12日 下午3:00:55
* @version V1.0
*
*/
@Service
public class DownloadService {
@Value("${resource.uploadurl}")
private String serverUrl;
@Resource
private ResourceCenterMapper resourceCenterMapper;
@Resource
private MyResourceMapper myResourceMapper;
/*文件下载*/
public void downloadFile(HttpServletRequest request, HttpServletResponse response, Integer schoolId, Integer centerId, ResourceCenterMapping rm){
String userAgent = request.getHeader("User-Agent");
String fileName=rm.getAccessoryName();
ResourceCenterAccessory ra = resourceCenterMapper.getFileInfo(schoolId, centerId, rm.getAccessoryId());
String path=ra.getUrl();
if (StringUtils.isNotBlank(path)) {
String str1=path.substring(0, path.indexOf("/resource/"));
String str2=path.substring(str1.length()+1, path.length());
path = serverUrl+"/"+str2;
}
if (fileName != null) {
//设置文件路径
File file = new File(path);
if (file.exists()) {
response.setHeader("content-type", "application/octet-stream");
response.setContentType("application/octet-stream");
// response.setContentType(MimeTypesUtil.getMimeType(path));
try {
// 针对IE或者以IE为内核的浏览器:
if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
} else {
// 非IE浏览器的处理:
fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
}
response.setHeader("Content-Disposition", "attachment;filename="+fileName);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
/**
* @Title: getResourceCenterMappingByCenterId
* @Description: (获取该资源下所有的附件信息)
* @param @param schoolId
* @param @param centerId
* @param @return 设定文件
* @return List<ResourceCenterMapping> 返回类型
* @throws
*/
public List<ResourceCenterMapping>getDownloadResourceCenterMappingByCenterId(Integer schoolId, Integer centerId, Integer accessoryId) {
return myResourceMapper.getDownloadResourceCenterMappingByCenterId(schoolId, centerId, accessoryId);
}
}
package cc.cloud.resourcecenter.config;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import lombok.extern.slf4j.Slf4j;
*//**
*
* <p>Title: AuthorizeFilter</p>
* <p>Description: 用来过滤 png jpg 这类资源/p>
* @date 2019年4月16日
*//*
@Component
@Slf4j
public class AuthorizeUploadFilter implements Filter {
private static Map<String, Object> allMimeTypes;
static {
allMimeTypes = new HashMap<String, Object>();
allMimeTypes.put("html", "text/html");
allMimeTypes.put("htm", "text/html");
allMimeTypes.put("jpg", "image/jpeg");
allMimeTypes.put("jpeg", "image/jpeg");
allMimeTypes.put("bmp", "image/bmp");
allMimeTypes.put("gif", "image/gif");
allMimeTypes.put("png", "image/png");
allMimeTypes.put("doc", "application/msword");
allMimeTypes.put("docx", "application/msword");
allMimeTypes.put("xls", "application/vnd.ms-excel");
allMimeTypes.put("xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
allMimeTypes.put("mp3", "audio/mpeg");
allMimeTypes.put("dot", "application/msword");
allMimeTypes.put("txt", "text/plain");
allMimeTypes.put("pdf", "application/pdf");
allMimeTypes.put("zip", "application/octet-stream");
allMimeTypes.put("rar", "application/octet-stream");
}
@Value("${resource.uploadurl}")
private String serverUrl;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
String url = req.getRequestURI();
String path = url.substring(req.getServletContext().getContextPath().length());
InputStream is = getInputStream(path);
HttpServletResponse res = (HttpServletResponse) response;
if (is == null) {
filterChain.doFilter(request, response);
return;
}
res.setContentType(getMimeType(path));
transmission(is, response.getOutputStream());
}
public void transmission(InputStream is, OutputStream os) throws IOException {
byte[] b = new byte[4096];
int k;
while ((k = is.read(b)) != -1) {
os.write(b, 0, k);
}
os.flush();
}
*//**
* <p>Title: getInputStream</p>
* <p>Description: </p>
* @param path
* @return
*//*
public InputStream getInputStream(String path) throws IOException {
File f = this.getFile(path);
return !f.exists() ? null : new FileInputStream(f);
}
*//**
* <p>Title: getFile</p>
* <p>Description: </p>
* @param path
* @return
*//*
private File getFile(String path) {
return (File) (path == null ? serverUrl : new File(serverUrl, path));
}
*//**
* 获得媒体类型
*
* @param path
* URL路径
* @return 媒体类型
*//*
private String getMimeType(String path) {
int k = path.lastIndexOf('.');
String t = path.substring(k + 1).toLowerCase();
String rs = (String) allMimeTypes.get(t);
return rs == null ? "application/octet-stream" : rs;
}
@Override
public void destroy() {
}
}